Wednesday 10 April 2019

java - How to read single JSON field with Jackson

Answer


Answer




I have a fairly large JSON response in which I'm interested in single field - status:



{
"title": "Some title",
"status": "pending",
"data": {
...
},

"meta": {
...
}
}


All I need to do is read the status value of the JSON response as string. I would prefer to not have to build a POJO to model it, because in my application I just need to store the JSON in a database on a particular status or discard it.



The application already uses Jackson for other more complicated cases so I'd prefer to stick with that library. So far all the examples I've found try to map the JSON to an object.


Answer




If the field required is a non-null text field, at the "first level" of the hierarchy (i.e., not any nested object) of a JSON object small enough to fit in main memory, a simple way of retrieving its value is using a method like



  public static String readField(String json, String name) throws IOException {
if (field != null) {
ObjectNode object = new ObjectMapper().readValue(json, ObjectNode.class);
JsonNode node = object.get(name);
return (node == null ? null : node.textValue());
}
return null;
}



ObjectNode is a generic Jackson class, not a POJO. If multiple values are to be used, the ObjectMapper should be cached (it is even thread-safe).



Running



System.out.println(readField(response, "status"));


using the JSON response string above, returns




pending


as expected. A similar solution can be found elsewhere in StackOverflow.



For very large JSON objects (e.g., stored in files), the streaming approach of Jackson should be used, as suggested in other answers.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...