如何解析Android中的复杂json响应

时间:2012-10-11 11:31:12

标签: java android json

我正在尝试解析JSON响应。我正在获得如下的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&名称值?

3 个答案:

答案 0 :(得分:3)

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);

由于播放列表是您的关键:值,您需要为它们编写自定义反序列化器。请查看GSON deserializing key-value to custom object了解如何做到这一点

答案 1 :(得分: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])
}

答案 2 :(得分: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;