当前位置: 代码迷 >> Eclipse >> json解析,该如何处理
  详细解决方案

json解析,该如何处理

热度:320   发布时间:2016-04-23 18:56:10.0
json解析
我在做android定位,我得到了json文件,希望只得到里面的城市名字,比如Mountain View,该如何做?
Java code
{   "status": "OK",   "results": [ {     "types": [ "street_address" ],     "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",     "address_components": [ {       "long_name": "1600",       "short_name": "1600",       "types": [ "street_number" ]     }, {       "long_name": "Amphitheatre Pkwy",       "short_name": "Amphitheatre Pkwy",       "types": [ "route" ]     }, {       "long_name": "Mountain View",       "short_name": "Mountain View",       "types": [ "locality", "political" ]     }, {       "long_name": "California",       "short_name": "CA",       "types": [ "administrative_area_level_1", "political" ]     }, {       "long_name": "United States",       "short_name": "US",       "types": [ "country", "political" ]     }, {       "long_name": "94043",       "short_name": "94043",       "types": [ "postal_code" ]     } ],     "geometry": {       "location": {         "lat": 37.4219720,         "lng": -122.0841430       },       "location_type": "ROOFTOP",       "viewport": {         "southwest": {           "lat": 37.4188244,           "lng": -122.0872906         },         "northeast": {           "lat": 37.4251196,           "lng": -122.0809954         }       }     }   } ] }


希望能提供代码 谢谢

------解决方案--------------------
json可以转list,然后取出来就行了
------解决方案--------------------
用json.jar
JSONOBject obj = JSONObject.from(str);

obj.getString("status");

......
------解决方案--------------------
try {
JSONObject obj = new JSONObject("jsonstr");
JSONArray jsonArray = obj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
JSONArray jsonArray2 = jo.getJSONArray("address_components");
for (int j = 0; j < jsonArray2.length(); j++) {
JSONObject jobj = jsonArray2.getJSONObject(j);
String short_name = jobj.getString("short_name");
System.out.println(j+": "+short_name);
}
}
} catch (JSONException e) {
e.printStackTrace();

}


[]解析成JSONArray ,{}解析成JSONObject,楼主应该看得明白吧,另外推荐楼主在eclipse里安一个json编辑器插件这样好分析json字符串的结构
------解决方案--------------------
探讨

json可以转list,然后取出来就行了

------解决方案--------------------
既然只要取文件名,完全不用json API反而更快
直接截取字符串就可以完成

Java code
String str=... //从Json文件读到的字符串int index1 = str.indexOf("\"long_name\": \"");int index2 = str.indexOf("\"",index1+14);String cityname = str.substring(index1,index2);
------解决方案--------------------
用json.jar
JSONOBject obj = JSONObject.from(str);

obj.getString("status");
  相关解决方案