无法解析谷歌的地方JSON响应 - org.json.JSONException

问题描述:

我收到来自谷歌API的JSON响应,我试图解析。但我得到org.json.JSONException。无法解析谷歌的地方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(); 

什么我错在这里做什么?

您将“name”和“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产生。

名称和的formatted_address是在JSON字符串都,但你正在试图获得它的JSONObject。相反使用类似

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