我想解析谷歌附近的地方回复,一个项目有这种格式:
"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"
但是我想用一个类似的对象来解析它:
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;
}
问题是如何访问" lat"和" lng" in" geometry"直接来自NearbyPlace类而不为每个节点创建另一个类?
答案 0 :(得分: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);
}
但是,由于vicinity
保留在内部几何类之外,您仍需要手动设置该值。 JsonNode
有必要的方法:
final JsonNode vicinityNode = placesNode.findPath("vicinity");
if (vicinityNode.isTextual()) {
place.vicinity = vicinityNode.textValue();
}
答案 1 :(得分:0)
由于您最终会得到NearbyPlace
的集合,因此您最好只需手动遍历JsonNode
。否则,你会谈论为集合重写反序列化,或编写一个可能令人讨厌的反序列化器。
以下示例是递归的。 Java中的递归是bad(目前),但编写起来很有趣。在制作应用中,我建议使用循环。
@Test
public void testNearbyPlaceDeserialization() throws Exception {
JsonNode jsonNode = objectMapper.readTree(new File("input.json"));
// or objectMapper.readValue(resultString, JsonNode.class);
ImmutableList<NearbyPlace> nearbyPlaces = readLatLng(jsonNode,
jsonNode.get("vicinity").asText(null),
ImmutableList.builder());
System.out.println(nearbyPlaces);
}
private static ImmutableList<NearbyPlace> readLatLng(JsonNode jsonNode,
String vicinity,
ImmutableList.Builder<NearbyPlace> placeBuilder) {
JsonNode latNode = jsonNode.get("lat");
JsonNode lngNode = jsonNode.get("lng");
if (latNode != null && lngNode != null) {
placeBuilder.add(NearbyPlace.builder()
.setLatitude(latNode.asDouble())
.setLongitude(lngNode.asDouble())
.setVicinity(vicinity)
.build());
} else {
jsonNode.elements().forEachRemaining((element) -> {
readLatLng(element, vicinity, placeBuilder);
});
}
return placeBuilder.build();
}
这将返回3 NearbyPlace
s。
答案 2 :(得分:0)
我能想到的最简单的解决方案是在@JsonCreator
类'构造函数上使用NearbyPlace
注释:
public class NearbyPlace extends BaseResponse {
private double latitude;
private double longitude;
@JsonProperty("vicinity")
private String vicinity;
@JsonCreator
public NearbyPlace(Map<String, Object> delegate) {
super();
this.latitude = (Double) delegate.get("geometry").get("location").get("lat");
this.latitude = (Double) delegate.get("geometry").get("location").get("lng");
}
}
如果传入的JSON缺少某些嵌套对象,即null
或geometry
,您可能希望针对location
添加一些检查。
有关详细信息,请参阅Jackson annotations documentation。