2010-09-20 24 views
2

我正在使用軟件包org.json軟件包:我需要幫助從java獲取json中的corect數據。這是我在JSON字符串:java中的json從列表中獲取正確的值

{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]} 

這是一個上市,這僅僅是一個測試,它將包含超過2項,所以我的問題是,我想所有地點的名稱,我想在我的android應用程序中使用名稱填充微調器。

我怎樣才能得到「名稱」:「馬爾默」等...... ???

回答

3

答案很簡單.... JSON元素以{這是一個JSON對象開始,而GetLocationsResults是一個JSON對象的JSON數組。實質上,我將JSON字符串翻譯爲以下代碼...

JSONObject rootJson = new JSONObject(jsonString); 
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult"); 

//Let's assume we need names.... 
String[] names = null; 
if (jsonArray != null) { 
    names = new String[jsonArray.length()]; 
    for (int i = 0; i < jsonArray.length(); i++) { 
     JSONObject json = jsonArray.getJSONObject(i); 
     names[i] = json.getString("Name"); 
    } 
} 

//Test 
for (String name: names) { 
    System.out.println(name); 
}