2014-03-27 33 views
19

我有响应如何将JSONObjects转换为JSONArray?

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

这里是我的代码

List<NameValuePair> param = new ArrayList<NameValuePair>(); 
JSONObject json = jParser.makeHttpRequest(url, "GET", param); 

    JSONObject songs= json.getJSONObject("songs"); 

如何歌曲转换为JSONArray?

回答

39

事情是这样的:

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)); 
} 
+0

漂亮的代码... #worked #plusone – BENN1TH

3

你的反应应该是这样的事情被定性为JSON数组。

{ 
    "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<arr.length(); i++){ 
    JSONObject o = arr.getJSONObject(i); 
    System.out.println(o); 
} 
0

反序列化反应需要使用HashMap

String resp = ...//String output from your source 

Gson gson = new GsonBuilder().create(); 
gson.fromJson(resp,TheResponse.class); 

class TheResponse{ 
HashMap<String,Song> songs; 
} 

class Song{ 
    String id; 
    String pos; 
}