如何将JSONObjects转换为JSONArray?

我有这样的回复:

{ "songs":{ "2562862600":{"id":"2562862600""pos":1}, "2562862620":{"id":"2562862620""pos":1}, "2562862604":{"id":"2562862604""pos":1}, "2573433638":{"id":"2573433638""pos":1} } } 

这是我的代码:

 List param = new ArrayList(); JSONObject json = jParser.makeHttpRequest(url, "GET", param); JSONObject songs= json.getJSONObject("songs"); 

如何将"songs"转换为JSONArray?

像这样的东西:

 JSONObject songs= json.getJSONObject("songs"); Iterator x = songs.keys(); JSONArray jsonArray = new JSONArray(); while (x.hasNext()){ String key = (String) x.next(); jsonArray.put(songs.get(key)); } 

你的响应应该像这样被认定为Json Array。

 { "songs":[ {"2562862600": {"id":"2562862600", "pos":1}}, {"2562862620": {"id":"2562862620", "pos":1}}, {"2562862604": {"id":"2562862604", "pos":1}}, {"2573433638": {"id":"2573433638", "pos":1}} ] } 

您可以按如下方式解析您的回复

 String resp = ...//String output from your source JSONObject ob = new JSONObject(resp); JSONArray arr = ob.getJSONArray("songs"); for(int i=0; i 

要反序列化响应需要使用HashMap

 String resp = ...//String output from your source Gson gson = new GsonBuilder().create(); gson.fromJson(resp,TheResponse.class); class TheResponse{ HashMap songs; } class Song{ String id; String pos; } 

更短,并具有jsonfunction:

 JSONObject songsObject = json.getJSONObject("songs"); JSONArray songsArray = songsObject.toJSONArray(songsObject.names());