先上一下需要解析的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();
}
}