杰克逊解析树的反应

Gen*_*per 5 java json jackson

我想解析谷歌附近的地方响应,一个项目有这种格式:

         "geometry" : {
            "location" : {
               "lat" : 75.22404,
               "lng" : 57.42276
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 95.2353532,
                  "lng" : 75.4427513
               },
               "southwest" : {
                  "lat" : 55.207256,
                  "lng" : 45.4045009
               }
            }
         },
         "vicinity" : "something"
Run Code Online (Sandbox Code Playgroud)

但是我想用一个像这样的对象来解析它:

public class NearbyPlace extends BaseResponse {

    @JsonProperty("how to access geometry->lat ?")
    private double latitude;

    @JsonProperty("how to access geometry->lng ?")
    private double longitude;

    @JsonProperty("vicinity")
    private String vicinity;
}
Run Code Online (Sandbox Code Playgroud)

问题是如何直接从NearbyPlace类访问"几何"中的"lat"和"lng"而不为每个节点创建另一个类?

dhk*_*hke 0

readTree()您可以使用和的组合treeToValue()

final String placesResponse = "...";
final ObjectMapper om;

NearbyPlace place = null;
final JsonNode placesNode = om.readTree(placesResponse);
final JsonNode locationNode = placesNode.findPath("geometry").findPath("location");
if (! locationNode.isMissingNode()) {
     place = om.treeToValue(locationNode, NearbyPlace.class);
}
Run Code Online (Sandbox Code Playgroud)

但是,由于vicinity保留在内部几何类之外,您仍然需要手动设置该值。JsonNode有必要的方法:

final JsonNode vicinityNode = placesNode.findPath("vicinity");
if (vicinityNode.isTextual()) {
    place.vicinity = vicinityNode.textValue();
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答,但我正在使用一个 ObjectMapper 来映射所有类类型: result = (T) objectMapper.readValue(resultString, aClass); 所以我需要在映射类中解决我的问题,在这种情况下:NearbyPlace (2认同)