1

我有以下 JSON 响应:

{
   "destination_addresses" : [ "Berlin, Deutschland" ],
   "origin_addresses" : [ "Mannheim, Deutschland" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "624 km",
                  "value" : 624195
               },
               "duration" : {
                  "text" : "5 Stunden, 53 Minuten",
                  "value" : 21156
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我的问题是:如何访问“距离”部分中的“文本”元素?

我现在有以下内容:

JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
JSONArray rows= null;
rows= object.getJSONArray("rows");
4

2 回答 2

2

您要么必须继续解析 JSONArray,例如:

for(int i = 0; i < rows.length; i++) {
    JSONArray elements = rows.getJSONArray(i);
    for(int j = 0; j < elements.length; j++) {   
        JSONObject current = elements.getJSONObject(j);
        String curText = current.getJSONObject("distance").getJSONObject("text");
    }    
} 

或者,您可以在 POJO 中表示您的 Json,并使用 Jackson 的 ObjectMapper 对其进行反序列化。

于 2016-08-08T10:47:32.823 回答
0

我不确定,但你可以尝试类似的方法

JSONArray rows = object.getJSONArray("rows");
      for (int i = 0; i < jsonObjInput.length(); i++) {
        JSONObject tmp = jsonObjInput.getJSONObject(i);
       }

克莱门特

于 2016-08-08T10:48:14.357 回答