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?
JSONArray objects have a function getJSONObject(int index) , you can loop through all of the JSONObjects by writing a simple for-loop: JSONArray array; for(int n = 0; n < array. length(); n++) { JSONObject object = array. getJSONObject(n); // do some stuff.... }
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With