先上一下需要解析的Json数据:
{
"results" : [
{
"address_components" : [
{
"long_name" : "荔湾区",
"short_name" : "荔湾区",
"types" : [ "sublocality", "political" ]
},
{
"long_name" : "广州",
"short_name" : "广州",
"types" : [ "locality", "political" ]
},
{
"long_name" : "广东省",
"short_name" : "广东省",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "中国",
"short_name" : "CN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "中国广东省广州荔湾区",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 23.15961330,
"lng" : 113.2768870
},
"southwest" : {
"lat" : 23.04186250,
"lng" : 113.17712080
}
},
"location" : {
"lat" : 23.1259510,
"lng" : 113.2442380
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 23.16699020,
"lng" : 113.30826770
},
"southwest" : {
"lat" : 23.08489920,
"lng" : 113.18020830
}
}
},
"types" : [ "sublocality", "political" ]
}
],
"status" : "OK"
}
上关键代码: 这只是解析了部分,但是其他部分都一样,不要忘记导入gson-2.1.jar包到程序中
public void parserJson(String str){ try { JSONObject jsonObject = new JSONObject(str); // 解析了最简单的status // String s = jsonObject.getString("status"); JSONArray jsonArray = jsonObject.getJSONArray("results"); for( int i=0;i<jsonArray.length();i++){ // 输入了formatted_address s = jsonArray.getJSONObject(i).getString("formatted_address"); System.out.println("formatted_address=======>"+s); // 输出了location里面的lat和lng两个值 double s1 = jsonArray.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat"); double s2 = jsonArray.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng"); System.out.println("lat:"+s1 + "-----" + "lng:"+s2); JSONArray jsonArray2 = jsonArray.getJSONObject(i).getJSONArray("address_components"); for( int j=0;j<jsonArray2.length();j++){ // 输出每一个long_name s = jsonArray2.getJSONObject(j).getString("long_name"); System.out.println(s); // 输出address_components里面的types JSONArray jsonArray3 = jsonArray2.getJSONObject(j).getJSONArray("types"); for( int k=0;k<jsonArray3.length();k++){ System.out.println(jsonArray3.get(k)); } } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }
}