我正在尝试在我的 android 程序中解析来自 google direction api 的 JSON 响应。这是下面的请求链接。我在这里跳过 JSON 响应,因为它太长了,只需单击链接即可显示。
我解析响应的代码:
try {
JSONObject responseObject = (JSONObject) new JSONTokener(responseString).nextValue();
this.responseString = responseObject.getString("status") ;
JSONArray routesArray = responseObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);
JSONArray legs ;
JSONObject leg ;
JSONArray steps ;
JSONObject dist;
Integer distance ;
if(route.has("legs")) {
legs = route.getJSONArray("legs");
leg = legs.getJSONObject(0) ;
steps = leg.getJSONArray("steps"); // EDIT : I had somehow missed this line before when copying the code from IDE to the website
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
JSONObject step = steps.getJSONObject(i);
if(step.has("distance")) {
dist = (JSONObject) step.get("distance");// throws exception
//I would like to take the distance value and do something with it
//if(dist.has("value"))
// distance = (Integer) dist.get("value") ;
}
}
}
else
this.responseString = "not found" ;
} catch ( Exception e) {
e.printStackTrace() ;
}
这会引发异常(再次跳过,因为 JSON 响应太大。堆栈跟踪显示了整个响应字符串):
org.json.JSONException: Expected ':' after polyline at character 13837 of {
"routes" : [
{
"bounds" : {
"northeast" : { ....
我尝试使用 getJSONObject
函数代替 get
,但我得到了同样的异常。
dist = step.getJSONObject("distance");
任何人都可以通过指出我在这里缺少什么来帮助我吗?我对 android 上的 parsin JSON 还不是很熟悉,所以我很可能在某个地方犯了一个愚蠢的错误。谢谢。
此站点上的另一个类似帖子,但不完全相同:JSON parsing of Google Maps API in Android App
最佳答案
由于您不太熟悉,我建议使用 Gson 解析 JSON,尤其是对于复杂的响应。这种情况更适合你的情况。
我使用 Gson 来解析来自 Google Maps API、Places API 等的响应...
您最好使用 Gson 来解析、映射数据和您的模型类。例如:
Gson gson = new Gson();
ModelClass modelClass= new ModelClass(); //or ArrayList<ModelClass>
modelClass= gson.fromJson(responseContent,ModelClass.class);
//where responseContent is your jsonString
Log.i("Web service response", ""+modelClass.toString());
https://code.google.com/p/google-gson/
对于命名差异(根据 webservice 中的变量),可以使用注释,如 @序列化名称。 (所以不需要使用Serializable)
您可以使用 for-each 循环并验证或操作来自模型类的数据。
for(Modelclass object: modelClass.getList()) {
}
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?
此外,尽可能使用 for-each 而不是 for(;;)。
检查这些:
Parsing data with gson from google places
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
How to parse google places json
我现在正在使用相同的 API,认为这对模型类也有帮助:
Displaying multiple routes using Directions API in Android
关于android - 解析来自 google direction api 的 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897820/