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.
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 ...
-
I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ...
-
I have a method in repository with this implementation which returns a Task Task > GetAllAppsRequestAsync(); I write the getter which cal...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
No comments:
Post a Comment