ddinchev ddinchev - 1 year ago 75
JSON Question

How to read single JSON field with Jackson

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


"title": "Some title",
"status": "pending",
"data": {
"meta": {

All I need to do is read the
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 Source

If the field required is a non-null text field, at the "first level" of the hierarchy (i.e., not any nested object), a quick way of retrieving its value is using a method like

  public static String readField(String json, String field) throws IOException {
    if (field != null) {
      ObjectNode object = new ObjectMapper().readValue(json, ObjectNode.class);
      JsonNode node = object.get(field);
      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).


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

using the JSON response string above, returns


as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download