29

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?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
NickUnuchek
  • 11,794
  • 12
  • 98
  • 138

5 Answers5

59

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));
}
Alireza Noorali
  • 3,129
  • 2
  • 33
  • 80
nikis
  • 11,166
  • 2
  • 35
  • 45
6

Even shorter and with json-functions:

JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());
plexus
  • 1,728
  • 1
  • 16
  • 12
  • tried this...but i no longer have the key names in the array...it just list them like this: 0 = "value", 1="value"....it changed the key names to 0,1,2,3 – Tim Boland Jul 26 '23 at 21:03
  • Yes, this is the expected outcome. If you need keys you should use a Map instead of an Array. – plexus Jul 31 '23 at 15:54
2

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);  
}
uzilan
  • 2,554
  • 2
  • 31
  • 46
0

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;
}
NickUnuchek
  • 11,794
  • 12
  • 98
  • 138
-3
JSONObject songs= json.getJSONObject("songs");

use JSONArray for direct conversion

JSONArray array = (JSONArray)songs.get("songs");
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56