怎样从这样一个JSON响应中获取一个值

huangapple 未分类评论50阅读模式
英文:

How do I get a value from such a JSON Response

问题

这是我从PlacesApi请求后得到的响应。但问题是,我无法获取"photo_reference"的值。问题还在于对象都在数组中,整个响应看起来很混乱。

以下是我在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;

    // 准备Activities请求
    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());
        }
    });

    // 添加到RequestQueue
    queue.add(getWeatherRequest);
}

这是错误:

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

这是Web中的响应:

{
   "candidates" : [
      {
         "photos" : [
            {
               "height" : 4160,
               "html_attributions" : [
                  "<a href=\"https://maps.google.com/maps/contrib/111684034547030396888\">Caroline Wood</a>"
               ],
               "photo_reference" : "CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ",
               "width" : 3120
            }
         ]
      }
   ],
   "status" : "OK"
}
英文:

This is What i get as a response from the PlacesApi after making a request.
But the issue is that i cant get the value of "photo_reference".
The issue is also the Objects being in Arrays and all , the whole response looks confusing.

Below is what i have tried in android studio Java

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

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

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

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

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

This is the Error

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

This is what the response is in the Web

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

答案1

得分: 0

使用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 json = "{
   \"candidates\" : [
      {
         \"photos\" : [
            {
               \"height\" : 4160,
               \"html_attributions\" : [
                  \"<a href=\\\"https://maps.google.com/maps/contrib/111684034547030396888\\\">Caroline Wood</a>\"
               ],
               \"photo_reference\" : \"CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ\",
               \"width\" : 3120
            }
         ]
      }
   ],
   \"status\" : \"OK\"
}";

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
英文:

Try to use Gson library for deserilization your response. http://tutorials.jenkov.com/java-json/gson.html

It's very simple way to get any values from response

At first need create class with response model

import java.util.List;

public class ResponseBody {

    public List&lt;Candidates&gt; candidates;

    public static class Candidates {
        public List&lt;Photos&gt; photos;

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

            public List&lt;String&gt; html_attributions;
        }
    }

}

Then just get your response as String and deserilize it:

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

        Gson gson = new Gson();

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

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

I got this:

responseBody = CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ

huangapple
  • 本文由 发表于 2020年5月3日 22:52:53
  • 转载请务必保留本文链接:https://java.coder-hub.com/61576506.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定