簡體   English   中英

無法解析Google Places JSON響應-org.json.JSONException

[英]Unable to parse google places JSON response - org.json.JSONException

我正在嘗試解析來自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();

我在這里做錯了什么?

您正在將“名稱”和“ formatted_address”視為JSONObject而不是普通的鍵/值對。

嘗試這個:

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

我不知道jsonResults是什么,但是很可能在這里做jsonResults.toString()

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

沒有提供有效的JSON字符串。 您應該檢查要處理的內容(執行Log.d("X", jsonResults.toString()); ),而不要顯示遠程API產生的內容。

name和formatted_address都是JSON中的String,但是您嘗試將其作為JsonObject進行獲取。 而是使用類似

placeDetails = "NAME: " + placeDetailsJsonArray.get("name").getAsString();
placeDetails += "ADDRESS: " + placeDetailsJsonArray.get("formatted_address").getAsString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM