2014-06-09 2 views
3

내 웹 사이트에서 gmaps를 만들고 싶습니다.자바 JSONObject 자식 가져 오기

좌표를 얻는 방법을 찾았습니다.

"location" : { 
      "lat" : 52.0860667, 
      "lng" : 21.0205308 
     }, 

을이 JSON에서 :

{ 
    "results" : [ 
     { 
     // body 
     "formatted_address" : "Puławska, Piaseczno, Polska", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 52.0979041, 
        "lng" : 21.0293984 
       }, 
       "southwest" : { 
        "lat" : 52.0749265, 
        "lng" : 21.0145743 
       } 
      }, 
      "location" : { 
       "lat" : 52.0860667, 
       "lng" : 21.0205308 
      }, 
      "location_type" : "GEOMETRIC_CENTER", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 52.0979041, 
        "lng" : 21.0293984 
       }, 
       "southwest" : { 
        "lat" : 52.0749265, 
        "lng" : 21.0145743 
       } 
      } 
     }, 
     "partial_match" : true, 
     "types" : [ "route" ] 
     } 
    ], 
    "status" : "OK" 
} 

나는 싶어.

나는 사용자 JSON - 간단한하기로 결정

<dependency> 
     <groupId>com.googlecode.json-simple</groupId> 
     <artifactId>json-simple</artifactId> 
     <version>1.1</version> 
    </dependency> 

내 코드는 다음과 같습니다

String coordinates = //JSON from google 

JSONObject json = (JSONObject)new JSONParser().parse(coordinates); 

그리고 난 첫 아이를 얻을 수 있습니다 : "결과"

String json2 = json.get("results").toString(); 

json2 올바른 표시 "결과"의 본문

하지만 "위치"아이들을 얻을 수 없습니다.

어떻게 만드시겠습니까?

덕분에

답변

8

난 당신이 JSONArrayjson.get("results")에 전화를 캐스팅 할 필요가 있다고 생각합니다.

e.e.

String coordinates = //JSON from google 

JSONObject json = (JSONObject)new JSONParser().parse(coordinates); 

JSONArray results = (JSONArray) json.get("results"); 

JSONObject resultObject = (JSONObject) results.get(0); 

JSONObject location = (JSONObject) resultObject.get("location"); 

String lat = location.get("lat").toString(); 

String lng = location.get("lng").toString() 

트릭은 당신이 비 직렬화하려는 json의 부분이 어떤 유형인지보고 적절한 유형으로 변환하는 것입니다.