首页 > 解决方案 > 如何从这样的 JSON 响应中获取值

问题描述

这是我发出请求后从 PlacesApi 得到的响应。但问题是我无法获得“photo_reference”的值。问题也是 Objects are in Arrays and all ,整个响应看起来令人困惑。

以下是我在 android studio Java 中尝试过的内容

private void getUserLocationImage(String mLocationName) {
    String url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input="+mLocationName+"&inputtype=textquery&fields=photos&key="+R.string.google_api;

    // prepare the Activities Request
    JsonObjectRequest getWeatherRequest = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray dataArray = response.getJSONArray("candidates");
                        JSONObject photosObj = dataArray.getJSONObject(0);
                        JSONArray photosArray = photosObj.getJSONArray("photos");
                        JSONObject photoRefObj = photosArray.getJSONObject(0);
                        String imageRef = photoRefObj.get("photo_reference").toString();


                        Toast.makeText(HomeLandingPageActivity.this, ""+imageRef, Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error.Response", error.toString());
        }
    });

    // add it to the RequestQueue
    queue.add(getWeatherRequest);
}

这是错误

org.json.JSONException: Index 0 out of range [0..0)

这就是 Web 中的响应

{
   "candidates" : [
      {
         "photos" : [
            {
               "height" : 4160,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/111684034547030396888\"\u003eCaroline Wood\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ",
               "width" : 3120
            }
         ]
      }
   ],
   "status" : "OK"
}

标签: javajsonandroid-studiogoogle-places-api

解决方案


尝试使用 Gson 库对您的响应进行反序列化。http://tutorials.jenkov.com/java-json/gson.html

这是从响应中获取任何值的非常简单的方法

首先需要使用响应模型创建类

import java.util.List;

public class ResponseBody {

    public List<Candidates> candidates;

    public static class Candidates {
        public List<Photos> photos;

        public static class Photos {
            public int height;
            public int width;
            public String photo_reference;

            public List<String> html_attributions;
        }
    }

}

然后只需将您的响应作为 String 并对其进行反序列化:

String json = "{\n" +
                "   \"candidates\" : [\n" +
                "      {\n" +
                "         \"photos\" : [\n" +
                "            {\n" +
                "               \"height\" : 4160,\n" +
                "               \"html_attributions\" : [\n" +
                "                  \"\\u003ca href=\\\"https://maps.google.com/maps/contrib/111684034547030396888\\\"\\u003eCaroline Wood\\u003c/a\\u003e\"\n" +
                "               ],\n" +
                "               \"photo_reference\" : \"CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ\",\n" +
                "               \"width\" : 3120\n" +
                "            }\n" +
                "         ]\n" +
                "      }\n" +
                "   ],\n" +
                "   \"status\" : \"OK\"\n" +
                "}";

        Gson gson = new Gson();

        ResponseBody responseBody = gson.fromJson(json, ResponseBody.class);

        System.out.println("responseBody = " + responseBody.candidates.get(0).photos.get(0).photo_reference);

我懂了:

responseBody = CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ

推荐阅读