Using Jackson to map object from specific node in JSON tree

前端 未结 1 1852
心在旅途
心在旅途 2020-12-16 14:31

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

相关标签:
1条回答
  • 2020-12-16 14:52

    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.

    0 讨论(0)
提交回复
热议问题