简体   繁体   English

如何在Android中解析复杂的JSON响应

[英]How to parse Complex json response in Android

I am trying to parse a JSON response. 我正在尝试解析JSON响应。 I am getting JSON response like below: 我收到如下所示的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",
        ]
    }

How can I access the id & name values? 如何访问ID和名称值?

I love GSON . GSON In this scenario you'd create two classes. 在这种情况下,您将创建两个类。

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
}

Then you can write 那你可以写

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

Since the playlists is coming to you as key:value you'd need to write a custom deserializer for them. 由于播放列表是作为key:value提供给您的,因此您需要为其编写自定义解串器。 Taje a look at GSON deserializing key-value to custom object for how to do that 看看GSON将键值反序列化到自定义对象的方法

In pseudocode. 用伪代码。 I don't remember exactly the JSON methods 我不记得确切的JSON方法

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

id = myList.getString("id")

To iterate over several lists, you'd better transform playlists to a JSONArray, then you can iterate over it. 要遍历多个列表,最好将播放列表转换为JSONArray,然后可以对其进行遍历。 If you can't do that, check the Android JSON API and check how to get all keys for a JSONObject and then iterate over the keys 如果无法做到这一点,请检查Android JSON API并检查如何获取JSONObject的所有键,然后遍历这些键

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

use google Gson. 使用Google Gson。 http://code.google.com/p/google-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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM