如何使用JSON获取价值?

时间:2018-04-08 16:44:04

标签: java android json

            Log.d("Hot Text:", response.toString());
            try {
                JSONArray array = response.getJSONArray("rows");
                JSONObject jsonObject = array.getJSONObject(0);
                JSONArray a = jsonObject.getJSONArray("elements");
                JSONObject js = a.getJSONObject(0);
                JSONObject b = js.getJSONObject("distance");
                value = b.getString("value");
                Log.d("TAG", "title:" + value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

如何为其他空间的存储获取“价值”?谢谢你

1 个答案:

答案 0 :(得分:0)

你可以这样做:

String text;
int value;
try {
     JSONObject jsonObject = new JSONObject(body);
     JSONArray rowArray = jsonObject.optJSONArray("rows");
     if(rowArray.length() > 0){
       JSONObject row = rowArray.optJSONObject(0);
       JSONArray elementArray = row.optJSONArray("elements");
       if(elementArray.length() > 0){
         JSONObject element = elementArray.optJSONObject(0);
         JSONObject distance = element.optJSONObject("distance");
         text = distance.optString("text");
         value = distance.optInt("value");
       }
     }
  } catch (JSONException e) {
    e.printStackTrace();
  }
Log.e("text", text);
Log.e("value", "value : " + value);