Reading value of nested key in JSON with Java (Jackson)

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 given path, or, if 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 actually model your structure as 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 resulting objects just like any Java objects.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)