2013-02-23 2 views
5

잭슨 JSON을 사용하여 구문 분석하려고하는 복잡한 JSON이 있습니다. latLng 객체로 들어가서 lat, lng 값을 꺼내는 방법에 대해서는 약간 혼란 스럽습니다. 이것은 내가 그것을 꺼내 지금까지 자바가 무엇Jackson JSON 파서 사용 : 복잡한 JSON?

{ 
    "results": [ 
     { 
      "locations": [ 
       { 
        "latLng": { 
         "lng": -76.85165, 
         "lat": 39.25108 
        }, 
        "adminArea4": "Howard County", 
        "adminArea5Type": "City", 
        "adminArea4Type": "County", 

: 이것은 JSON의 일부입니다

public class parkJSON 
{ 
    public latLng _latLng; 

    public static class latLng 
    { 
     private String _lat, _lng; 
     public String getLat() { return _lat; } 
     public String getLon() { return _lng; } 
    } 
} 

및 해결

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally 
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
parkJSON geo = mapper.readValue(parse, parkJSON.class); 

System.out.println(mapper.writeValueAsString(geo)); 
String lat = geo._latLng.getLat(); 
String lon = geo._latLng.getLon(); 
output = lat + "," + lon; 
System.out.println("Found Coordinates: " + output); 

이것은 어떻게 미래의 참조를 위해 Tree Model을 사용하여 문제를 해결했습니다.

  ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally 
      mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);     
      JsonNode rootNode = mapper.readTree(parse); 
      JsonNode firstResult = rootNode.get("results").get(0); 
      JsonNode location = firstResult.get("locations").get(0); 
      JsonNode latLng = location.get("latLng"); 
      String lat = latLng.get("lat").asText(); 
      String lng = latLng.get("lng").asText(); 
      output = lat + "," + lng; 
      System.out.println("Found Coordinates: " + output); 

답변

4

위 입력 구조에 관심이있는 사람이라면 lat와 lng 전체 매핑이 Jackson에서 제공하는 다양한 접근 방식 중 가장 적합하지 않을 것입니다. 이는 데이터에 다른 레이어를 나타내는 클래스를 작성해야하기 때문입니다.

당신이이 클래스를 정의 할 필요없이 이러한 필드를 추출 할 수 있습니다 잭슨에 의해 제공되는 두 가지 대안이 있습니다

  1. The tree model 트리를 순회하고있는 데이터를 추출하는 탐색 방법을 제공하고이
  2. Simple data binding은 JSON 문서를지도 또는 목록에 매핑 한 다음이 컬렉션에서 제공하는 메소드로 탐색 할 수 있습니다.

잭슨 설명서에는 두 가지 기술에 대한 예제가 들어 있으므로 프로그램에 적용하면 안됩니다. 디버거를 사용하여 파서가 만든 데이터 구조를 조사하여 문서가 어떻게 매핑되었는지 확인하십시오.

+0

트리 모델 방법을 사용하여 작업했습니다. –

+0

ObjectMapper mapper = new ObjectMapper(); // 전역으로 재사용하거나 공유 할 수 있습니다. mapper.configure (DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode rootNode = mapper.readTree (구문 분석); JsonNode firstResult = rootNode.get ("results"). get (0); JsonNode location = firstResult.get ("locations"). get (0); JsonNode latLng = location.get ("latLng"); String lat = latLng.get ("lat"). asText(); String lng = latLng.get ("lng"). asText(); –

+0

정말 대단합니다 :-) 프로젝트에 행운이 있기를 바랍니다. – fvu