2013-02-05 29 views
4

JSON響應值看起來像這樣"types" : [ "sublocality", "political" ]。如何獲得類型的第一個值或如何獲得單詞sublocality?如何在android中獲取json數組值?

+1

這不是一個有效的JSON。你確定它不包含大括號:'{}'? –

+0

@NikitaBeloglazov看到這個鏈接http://maps.googleapis.com/maps/api/geocode/json?address=adyar&sensor=true – Yugesh

+0

@NikitaBeloglazov這是一個JSON數組。 –

回答

13
String string = yourjson; 

JSONObject o = new JSONObject(yourjson); 
JSONArray a = o.getJSONArray("types"); 
for (int i = 0; i < a.length(); i++) { 
    Log.d("Type", a.getString(i)); 
} 

如果您僅解析上面提供的行,這將是正確的。請注意,要訪問GoogleMaps地理編碼中的類型,您應該獲得一組結果,而不是address_components,然後您可以訪問對象components.getJSONObject(index)。

這是一個簡單的實現,只解析formatted_address - 我需要在我的項目中。

private void parseJson(List<Address> address, int maxResults, byte[] data) 
{ 
    try { 
     String json = new String(data, "UTF-8"); 
     JSONObject o = new JSONObject(json); 
     String status = o.getString("status"); 
     if (status.equals(STATUS_OK)) { 

      JSONArray a = o.getJSONArray("results"); 

      for (int i = 0; i < maxResults && i < a.length(); i++) { 
       Address current = new Address(Locale.getDefault()); 
       JSONObject item = a.getJSONObject(i); 

       current.setFeatureName(item.getString("formatted_address")); 
       JSONObject location = item.getJSONObject("geometry") 
         .getJSONObject("location"); 
       current.setLatitude(location.getDouble("lat")); 
       current.setLongitude(location.getDouble("lng")); 

       address.add(current); 
      } 

     } 
    catch (Throwable e) { 
     e.printStackTrace(); 
    } 

} 
+0

ya使用格式地址是正確的事情。 – Yugesh

1

您應該解析該JSON以獲取這些值。您可以在Android中使用JSONObject和JSONArray類,也可以使用Google GSON這樣的庫從JSON獲取POJO。

1

我會堅持你使用GSON。我創建了一個解析相同地圖響應的演示。你可以找到完整的演示here。此外,我創建了一個全局GSON解析器類,可用於輕鬆解析JSON中的任何響應。

相關問題