Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...