2011-06-14 68 views
0

我的版本是Android 2.2 Google API 8,我從模擬器運行。我嘗試訪問此JSON對象中的長訪問位置。我使用後我得到這個Android - 如何解析JSONObject和JSONArrays

InputStream instream = entity.getContent(); 

JSONObject myAwway = new JSONObject(convertStreamToString(instream)); 

谷歌文檔說,它返回一個數組,但與周圍的大括號它看起來像一個對象。

我需要訪問位置字段中的緯度和經度,並存儲爲雙打。

我已經搜索,但似乎只能找到簡單文件的幫助。

{ 
    "results" : [ 
     { 
     "address_components" : [ 
      { 
       "long_name" : "20059", 
       "short_name" : "20059", 
       "types" : [ "postal_code" ] 
      }, 
      { 
       "long_name" : "Washington D.C.", 
       "short_name" : "Washington D.C.", 
       "types" : [ "locality", "political" ] 
      }, 
      { 
       "long_name" : "District of Columbia", 
       "short_name" : "DC", 
       "types" : [ "administrative_area_level_1", "political" ] 
      }, 
      { 
       "long_name" : "United States", 
       "short_name" : "US", 
       "types" : [ "country", "political" ] 
      } 
     ], 
     "formatted_address" : "Washington D.C., DC 20059, USA", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 38.924920, 
        "lng" : -77.0178720 
       }, 
       "southwest" : { 
        "lat" : 38.9189910, 
        "lng" : -77.02261200000001 
       } 
      }, 
      "location" : { 
       "lat" : 38.92177780, 
       "lng" : -77.01974260 
      }, 
      "location_type" : "APPROXIMATE", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 38.92510312068017, 
        "lng" : -77.01709437931984 
       }, 
       "southwest" : { 
        "lat" : 38.91880787931983, 
        "lng" : -77.02338962068018 
       } 
      } 
     }, 
     "types" : [ "postal_code" ] 
     } 
    ], 
    "status" : "OK" 
} 

回答

2
JSONObject location = myAwway.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location"); 
double lat = location.getDouble("lat"); 
double lng = location.getDouble("lng"); 

'results'JSONArray可能是Google文檔建議的數組。他們剛剛將它封裝在帶有狀態的JSONObject中,以便在嘗試處理返回的值之前檢查狀態。

4
JSONObject jObject = new JSONObject(convertStreamToString(instream)); 
JSONArray results = jObject.getJSONArray("result"); 
JSONObject geometry = results.getJSONObject(2); 
JSONObject bounds = geometry.getJSONObject("bounds"); 
JSONObject northeast = geometry.getJSONObject("northeast"); 

double nLat = Double.parseDouble(northeast.getString("lat").toString()); 
double nLng = Double.parseDouble(northeast.getString("lng").toString()); 

這應該給你緯度/經度爲東北爲雙打。東南部同樣只是東南部的東南部。

+0

JSONArray結果中只有一個元素。 – 2011-06-14 22:00:00

+0

哎呀,好的電話。 – 2011-06-14 23:29:01