无法解析谷歌放置JSON响应 - org.json.JSONException

时间:2015-06-21 14:24:43

标签: java android json google-places-api

我正在接收来自Google Places API的JSON响应,我正在尝试解析。但是我得到了org.json.JSONException。

这是我的JSON回复。

https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJbf6hrtZ2AjoRwUPd_nrhVjM&key=AIzaSyBWKQHS39-SYUNxEEAry1FxrMET2NwhqxE

我使用以下代码检索格式化的地址。

  try {

        Log.e("test-ttt", jsonResults.toString());

        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());

        JSONObject placeDetailsJsonArray = jsonObj.getJSONObject("result");

        // Extract the Place descriptions from the results
        placeDetails = "NAME: " + placeDetailsJsonArray.getJSONObject("name").toString();
        placeDetails += "ADDRESS: " + placeDetailsJsonArray.getJSONObject("formatted_address").toString();


    } catch (JSONException e) {
        Log.e(TAG, "Cannot process JSON results", e);
    }

这是我得到的logcat异常:

org.json.JSONException: Value South Point School at name of type java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:100)
        at org.json.JSONObject.getJSONObject(JSONObject.java:578)
        at manasthemarvel.triptimeline.PlaceAPI.getPlaceDetails(PlaceAPI.java:78)
        at manasthemarvel.triptimeline.placeInfo.doInBackground(placeInfo.java:14)
        at manasthemarvel.triptimeline.placeInfo.doInBackground(placeInfo.java:10)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)


        // Extract the Place descriptions from the results
        placeDetails = "NAME: " + placeDetailsJsonArray.getJSONObject("name").toString();
        placeDetails += "ADDRESS: " + placeDetailsJsonArray.getJSONObject("formatted_address").toString();

我在这里做错了什么?

3 个答案:

答案 0 :(得分:2)

您将“name”和“formatted_address”视为JSONObject而不是普通的键/值对。

试试这个:

JSONObject placeDetailsJsonArray = jsonObj.getJSONObject("result");
String name = placeDetailsJsonArray.getString("name");

答案 1 :(得分:0)

我不知道jsonResults是什么,但最有可能在这里做jsonResults.toString()

JSONObject jsonObj = new JSONObject(jsonResults.toString());

未提供有效的JSON字符串。您应该检查您正在处理的内容(执行Log.d("X", jsonResults.toString());),而不是显示远程API生成的内容。

答案 2 :(得分:0)

name和formatted_address都是JSON中的String,但是你试图将它作为JsonObject。而是使用像

这样的东西
placeDetails = "NAME: " + placeDetailsJsonArray.get("name").getAsString();
placeDetails += "ADDRESS: " + placeDetailsJsonArray.get("formatted_address").getAsString();