Java – use Jackson to map objects from specific nodes in the JSON tree
Can Jackson's objectmapper ungroup from a specific node (and "down") in the JSON tree?
Use cases are extensible document formats I want to go through the tree and publish the current path to the extensible plug-in set to see whether the user is using it and the plug-ins that know what to do in this part of the document
I want plug-in authors not to have to deal with the low-level details of jsonnode or stream API; Instead, just pass some context and a specific jsonode, and then use the lovely and convenient objectmapper to ungroup the instances of their classes, considering the nodes passed at 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 that you want to resolve the coordinate node to the following Java classes:
public class Coordinates { private Double latitude; private Double longitude; // Default constructor,getters and setters omitted }
To do this, parse the whole JSON into jsonnode and 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 coordinate node and use objectmapper to resolve it to coordinate class:
JsonNode coordinatesNode = node.at("/address/coordinates"); Coordinates coordinates = mapper.treeToValue(coordinatesNode,Coordinates.class);
JSON pointer is a path language that traverses JSON For more details, please refer to RFC 6901 It has been available in Jackson since version 2.3