简体   繁体   中英

How to convert JSONObjects to JSONArray?

I have a response like this:

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

Here is my code:

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

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

How do I convert "songs" to a JSONArray?

Something like this:

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

Even shorter and with json-functions:

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

Your response should be something like this to be qualified as Json Array.

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

You can parse your response as follows

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

To deserialize the response need to use 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;
}
JSONObject songs= json.getJSONObject("songs");

使用 JSONArray 进行直接转换

JSONArray array = (JSONArray)songs.get("songs");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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