Your root node doesn't have a customerSessionId, it has a HotelListResponse. Get that first.
//other methods
public void basicTreeModelRead()
{
JsonNode innerNode = rootNode.get("HotelListResponse"); // Get the only element in the root node
// get an element in that node
JsonNode aField = innerNode.get("customerSessionId");
//the customerSessionId has a String value
String myString = aField.asText();
System.out.println("customerSessionId is:" + myString);
}
This prints
customerSessionId is:0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2
Another way to get the inner element, with .at() method:
rootNode.at("/HotelListResponse/customerSessionId")
With Jackson's tree model (JsonNode), you have both "literal" accessor methods (get), which returns null for missing value, and "safe" accessors (path), which allow you to traverse "missing" nodes. So, for example:
JsonNode root = mapper.readTree(inputSource);
int h = root.path("response").path("history").getValueAsInt();
which would return the value at the given path, or, if the path is missing, 0 (default value).
But more conveniently, you can just use JSON pointer expression:
int h = root.at("/response/history").getValueAsInt();
There are other ways too, and often it is more convenient to model your structure as a Plain Old Java Object (POJO). Your content could fit something like:
public class Wrapper {
public Response response;
}
public class Response {
public Map<String,Integer> features; // or maybe Map<String,Object>
public List<HistoryItem> history;
}
public class HistoryItem {
public MyDate date; // or just Map<String,String>
// ... and so forth
}
and if so, you would traverse the resulting objects just like any Java object.
Use Jsonpath
Integer h = JsonPath.parse(json).read("$.response.repository.history", Integer.class);
Provided that you have already read this object into JsonNode, you can do it like this:
String content = jsonNode.get("data").textValue();
UPD: since you're using a streaming parser, this example on Jackson usage might help.
UPD: the method name is now textValue() - docs
When we try to fetch data in form of string from JsonNode,we usually use asText, but we should use textValue instead.
asText: Method that will return a valid String representation of the container value, if the node is a value node (method isValueNode() returns true), otherwise empty String.
textValue: Method to use for accessing String values. Does NOT do any conversions for non-String value nodes; for non-String values (ones for which isTextual() returns false) null will be returned. For String values, null is never returned (but empty Strings may be)
So Let's take an example,
JsonNode getJsonData(){
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("anyParameter",null);
return node;
}
JsonNode node = getJsonData();
json.get("anyParameter").asText() // this will give output as "null"
json.get("").textValue() // this will give output as null