2016-11-11 30 views
1

我使用的以下映射一個JSON響應於地圖如何從地圖解析嵌套JSON <字符串,對象>

Map<String, Object> apiResponse = restTemplate.postForObject("https://maps.googleapis.com/maps/api/geocode/json?address="+defaultLocation+"&key="+API_KEY, httpEntity, Map.class, Collections.EMPTY_MAP); 

我可以使用下面,以輸出整個JSON爲字符串

String jsonResponse = apiResponse.get("results").toString(); 

不過,我想是一個嵌套的值,它是results->geometry->location

我已經嘗試了一些解決方案與JSONArrays, JSONObjects, Substring,但不能讓他們的工作。

響應JSON:

{ 
    "results" : [ 
     { 
     "address_components" : [ 
      { 
       "long_name" : "Auckland", 
       "short_name" : "Auckland", 
       "types" : [ "locality", "political" ] 
      }, 
      { 
       "long_name" : "Auckland", 
       "short_name" : "Auckland", 
       "types" : [ "administrative_area_level_2", "political" ] 
      }, 
      { 
       "long_name" : "Auckland", 
       "short_name" : "Auckland", 
       "types" : [ "administrative_area_level_1", "political" ] 
      }, 
      { 
       "long_name" : "New Zealand", 
       "short_name" : "NZ", 
       "types" : [ "country", "political" ] 
      } 
     ], 
     "formatted_address" : "Auckland, New Zealand", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : -36.660571, 
        "lng" : 175.287137 
       }, 
       "southwest" : { 
        "lat" : -37.065475, 
        "lng" : 174.4438016 
       } 
      }, 
      "location" : { 
       "lat" : -36.8484597, 
       "lng" : 174.7633315 
      }, 
      "location_type" : "APPROXIMATE", 
      "viewport" : { 
       "northeast" : { 
        "lat" : -36.660571, 
        "lng" : 175.287137 
       }, 
       "southwest" : { 
        "lat" : -37.065475, 
        "lng" : 174.4438016 
       } 
      } 
     }, 
     "place_id" : "ChIJ--acWvtHDW0RF5miQ2HvAAU", 
     "types" : [ "locality", "political" ] 
     }, 
     { 
     "address_components" : [ 
      { 
       "long_name" : "Auckland", 
       "short_name" : "Auckland", 
       "types" : [ "political", "sublocality", "sublocality_level_1" ] 
      }, 
      { 
       "long_name" : "Auckland", 
       "short_name" : "Auckland", 
       "types" : [ "locality", "political" ] 
      }, 
      { 
       "long_name" : "Auckland", 
       "short_name" : "Auckland", 
       "types" : [ "administrative_area_level_2", "political" ] 
      }, 
      { 
       "long_name" : "Auckland", 
       "short_name" : "Auckland", 
       "types" : [ "administrative_area_level_1", "political" ] 
      }, 
      { 
       "long_name" : "New Zealand", 
       "short_name" : "NZ", 
       "types" : [ "country", "political" ] 
      }, 
      { 
       "long_name" : "1010", 
       "short_name" : "1010", 
       "types" : [ "postal_code" ] 
      } 
     ], 
     "formatted_address" : "Auckland, 1010, New Zealand", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : -36.8364659, 
        "lng" : 174.7838398 
       }, 
       "southwest" : { 
        "lat" : -36.8621041, 
        "lng" : 174.7503805 
       } 
      }, 
      "location" : { 
       "lat" : -36.8484597, 
       "lng" : 174.7633315 
      }, 
      "location_type" : "APPROXIMATE", 
      "viewport" : { 
       "northeast" : { 
        "lat" : -36.8364659, 
        "lng" : 174.7838398 
       }, 
       "southwest" : { 
        "lat" : -36.8621041, 
        "lng" : 174.7503805 
       } 
      } 
     }, 
     "place_id" : "ChIJuZqpSPtHDW0R4LOiQ2HvAAU", 
     "types" : [ "political", "sublocality", "sublocality_level_1" ] 
     } 
    ], 
    "status" : "OK" 
} 

任何幫助將不勝感激。

+0

請分享您的json輸出和代碼你試過 –

+0

@PavneetSingh我已經添加了響應JSON。代碼已經過去了,所以我可以添加我嘗試過的。我真的對最好的方法感興趣,如果你有一個? – Yonkee

+0

檢查這個答案。這是你在找什麼。 http://stackoverflow.com/questions/40407198/dynamic-json-structure-to-java-structure/40433552#40433552 – Yoram

回答

3
JSONObject obj=new JSONObject(jsonresult); 
// get result array 
JSONArray resultsarray= obj.getJSONArray("results"); 
for (int i=0;i<resultsarray.length(),i++){ 
     // get Objects using index 
     JSONObject jsonobject= results.getJSONObject(i); 
     // get geometry object 
     JSONObject geometry= jsonobject.getJSONObject("geometry"); 
     // get location object from geometry 
     JSONObject location= geometry.getJSONObject("location"); 

     // get location values from location object 
     double lat = location.optDouble("lat",0.0); 
     double long = location.optDouble("lng",0.0); 
} 

關於optDouble

public double optDouble(String key, double defaultValue) { 

獲取與關鍵,或將默認值相關的可選雙如果 不存在這樣的鍵,或者如果它的值是不是數字。如果值爲 一個字符串,則會嘗試將其評估爲數字。

+0

你正在使用哪個JSONObject?我不支持getJSONArray – Yonkee

+0

@Yonkee我使用'org.json.JSONObject' –

+1

繁榮,它的工作。我認爲我在調查過程中使用了錯誤的JSON庫。謝謝你的幫助。 – Yonkee

0

理想情況下,您希望像使用JS那樣使用相同的本機符號訪問屬性。事情是這樣的:

String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address; 
String responseStr = fetch(url); 
JsonHelper response = JsonHelper.forString(responseStr); 

String status = (String) response.getValue("status"); 
if(status != null && status.equals("OK")) { 
    lat = (Double) response.getValue("results[0].geometry.location.lat");   
    lng = (Double) response.getValue("results[0].geometry.location.lng"); 
} 

以下JsonHelper類代碼(從jello-framework拍攝)可以讓你這樣做。

package jello.common; 

import java.util.List; 

import com.google.gson.Gson; 
import java.util.AbstractMap; 

public class JsonHelper { 

    private Object json; 

    public JsonHelper(String jsonString) { 
     Gson g = new Gson(); 
     json = g.fromJson(jsonString, Object.class); 
    } 

    public static JsonHelper forString(String jsonString) { 
     return new JsonHelper(jsonString); 
    } 

    @SuppressWarnings("unchecked") 
    public Object getValue(String path) { 
     Object value = json; 
     String [] elements = path.split("\\."); 
     for(String element : elements) { 
      String ename = element.split("\\[")[0]; 

      if(AbstractMap.class.isAssignableFrom(value.getClass())) { 
       value = ((AbstractMap<String, Object>) value).get(ename); 

       if(element.contains("[")) { 
        if(List.class.isAssignableFrom(value.getClass())) { 
         Integer index = Integer.valueOf(element.substring(element.indexOf("[")+1, element.indexOf("]"))); 
         value = ((List<Object>) value).get(index); 
        } 
        else { 
         return null; 
        } 
       } 
      } 
      else { 
       return null; 
      } 
     } 

     return value; 
    } 
} 
+0

我已經實現了這一點,但仍不確定如何獲得嵌套值? JSONHelper jsonHelper = new JSONHelper(apiResponse.toString()); – Yonkee

0

使用傑克遜API用於解析,它會很容易

 ObjectMapper mapper = new ObjectMapper(); 
     JsonNode node = mapper.readTree(json); 
     if(node.get("results").isArray()){ 
      for(int i=0; i <= node.get("results").size()-1; i++){ 
       System.out.println(node.get("results").get(i)); 
      } 
0

我用GSON API和能夠得到的位置。試試這個:

代碼::

Gson gson = new Gson(); 

    String json = "your json"; 

    JsonObject map = gson.fromJson(json, JsonObject.class); // to be replaced with your restTemplate call 
    JsonArray arr = map.getAsJsonArray("results"); 

    for (Object j : arr) { 
     System.out.println(((JsonObject) j).get("geometry").getAsJsonObject().get("location")); 
    } 

控制檯輸出::

{"lat":-36.8484597,"lng":174.7633315} 
{"lat":-36.8484597,"lng":174.7633315} 

所以最好只得到響應的JsonObject而不是Map,你就可以閱讀location

相關問題