javajsonjackson

Using Jackson to map object from specific node in JSON tree


Is it possible to have Jackson's ObjectMapper unmarshall only from a specific node (and 'down') in a JSON tree?

The use case is an extensible document format. I want to walk the tree, and then publish the current path to an extensible set of plugins, to see if the user is using and plugins that know what to do with that part of the document.

I'd like for plugin authors to not have to deal with the low-level details of JsonNode or the streaming API; instead, just be passed some context and a specific JsonNode, and then be able to use the lovely and convenient ObjectMapper to unmarshall an instance of their class, considering the node passed as the root of the tree.


Solution

  • Consider the following JSON:

    {
      "firstName": "John",
      "lastName": "Doe",
      "address": {
        "street": "21 2nd Street",
        "city": "New York",
        "postalCode": "10021-3100",
        "coordinates": {
          "latitude": 40.7250387,
          "longitude": -73.9932568
        }
      }
    }
    

    And consider you want to parse the coordinates node into the following Java class:

    public class Coordinates {
    
        private Double latitude;
    
        private Double longitude;
        
        // Default constructor, getters and setters omitted
    }
    

    To do it, parse the whole JSON into a JsonNode with ObjectMapper:

    String json = "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"address\":{\"street\":"
                + "\"21 2nd Street\",\"city\":\"New York\",\"postalCode\":\"10021-3100\","
                + "\"coordinates\":{\"latitude\":40.7250387,\"longitude\":-73.9932568}}}";
    
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(json);
    

    Then use JSON Pointer to query the coordinates node and use ObjectMapper to parse it into the Coordinates class:

    JsonNode coordinatesNode = node.at("/address/coordinates");
    Coordinates coordinates = mapper.treeToValue(coordinatesNode, Coordinates.class);
    

    JSON Pointer is a path language to traverse JSON. For more details, check the RFC 6901. It is available in Jackson since the version 2.3.