EngineerBetter EngineerBetter - 1 year ago 101
Java Question

Using Jackson to map object from specific node in JSON tree

Is it possible to have Jackson's

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
or the streaming API; instead, just be passed some context and a specific
, and then be able to use the lovely and convenient
to unmarshall an instance of their class, considering the node passed as the root of the tree.

Answer Source

Consider, for example, you have the following JSON:

    "address" : { "street" : "2940 5th Ave", "zip" : 980021 },   
    "dimensions" : [ 10.0, 20.0, 15.0 ] 

You can parse it into a JsonNode and use JSON Pointer to select a node and then convert it into a POJO:

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree("{\r\n    \"address\" : { \"street\" : \"2940 5th Ave\", \"zip\" : 980021 },   \r\n    \"dimensions\" : [ 10.0, 20.0, 15.0 ] \r\n}");

JsonNode addressNode ="/address");
Address address = mapper.treeToValue(addressNode, Address.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download