Wednesday, April 10, 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.
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
When the left part is an object instance, you use -> . Otherwise, you use :: . This means that -> is mostly used to access instance m...
-
i've started to create my website, but now i have few doubts. I've searched, that MySqli object oriented is good to use beca...
-
I've been asked to update some Excel 2003 macros, but the VBA projects are password protected, and it seems there's a lack of docume...
No comments:
Post a Comment