2012-10-11 76 views
0

我想解析一個JSON響應。我得到JSON響應象下面這樣:如何在Android中解析複雜的json響應

"libraryLastModified" : "2012-10-10 03:57:26", 
"playlists" : { "10063" : { "id" : "10063", 
     "name" : "Favorites", 
     "songs" : [ "10006134", 
      "10006053", 
      "10006274", 
      "10006167", 
     ] 
    }, 
    "10157" : { "id" : "10157", 
     "name" : "80s", 
     "songs" : [ "10006694", 
      "10006695", 
      "10006697", 
      "10006699", 
      "10006698", 
     ] 
    } 

我如何訪問ID & name值?

回答

1

在僞代碼。我不記得確切的JSON方法

JSONObject mainObj = parseJson 
JSONObject playLists = mainObj.getJSONObject("playlists") 
JSONObject myList = playList.getJSONObject("10063") 

id = myList.getString("id") 

遍歷多個列表,你最好變換播放列表的JSONArray,那麼你可以通過它進行迭代。如果你不能做到這一點,檢查了Android JSON API,並檢查如何讓所有鍵一個JSONObject,然後遍歷鍵

for(int i=0;i<playlistKeys.length;i++){ 
    playlistObj = playLists.getJSONObject(playlistsKey[i]) 
} 
+0

這工作,但如何使其迭代,因爲我有多個播放列表10063,10064 .... – user1737884

+0

檢查我的更新答案 – Maragues

+0

我如何獲得鍵值? – user1737884

3

I GSON。在這種情況下,你會創建兩個類。

public class PLayList { 
private int id; 
private String name; 
private List<Integer> songs; 
//getters and setters 
} 

public class Library { 
private Date libraryLastModified; 
private List<Playlist> playlists; 
//getters and setters 
} 

然後,你可以寫

Gson gson = new Gson(); 
Library result = gson.fromJson(theInput, Library.class); 

由於播放列表來到你的關鍵:值你需要編寫一個自定義解串器他們。 Taje一看GSON deserializing key-value to custom object如何做到這一點

0

使用谷歌GSON。 http://code.google.com/p/google-gson/

class Response{ 
Date libraryLastModified; 
Playlist []playlists; 

class Playlist{ 
    Long id; 
    String name; 
    Long[] songs; 
} 

} 
String _response=... //Your response from web 
Response response = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create().fromJson(_response, Response.class); 

String songName = response.playlists[0].name; 
+0

其Throwin異常'10-11 12:51:08.615:W/System.err(359):com.google.gson.JsonSyntaxException:java.text.ParseException:Unparseable date :2012-10-10 03:57:26 \t at com.google.gson.DefaultTypeAdapters $ DefaultJavaSqlDateTypeAdapter.deserialize(DefaultTypeAdapters.java:416)' – user1737884