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 documen
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.