Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through JSONObject

Tags:

json

android

I parse the response from a web service into a JSONObject, which when logged, looks as follows:

{"Preferences":"{Pref1=Apple, Pref2=Pear}"}

I understand how to ask for the Preferences tag e.g. jsonObject.get("Preferences"). However, I do not understand what object I am getting back nor how to iterate over it. How can I iterate over the object returned by jsonObject.get("Preferences")?

like image 858
RunLoop Avatar asked Dec 08 '22 14:12

RunLoop


2 Answers

the object returned by preferences is a String. If you want to iterate through the childs of Preferences you may want to change the structure, to for example:

{"Preferences":{"Pref1":"Apple", "Pref2":"Pear"}}

and parse it like this:

JSONObject inputJSON = new JSONObject("{\"Preferences\":{\"Pref1\":\"Apple\", \"Pref2\":\"Pear\"}}");
JSONObject preferencesJSON = inputJSON.getJSONObject("Preferences");
Iterator<String> keysIterator = preferencesJSON.keys();
while (keysIterator.hasNext()) 
{
        String keyStr = (String)keysIterator.next();
        String valueStr = preferencesJSON.getString(keyStr);
}

alternatively, if you want to keep your structure, you can parse the returned string by the Preferences object like this:

JSONObject inputJSON = new JSONObject("{\"Preferences\":\"{Pref1=Apple, Pref2=Pear}\"}");
String preferencesStr = inputJSON.getString("Preferences");
JSONObject preferencesJSON = new JSONObject(preferencesStr);
Iterator<String> keysIterator = preferencesJSON.keys();
while (keysIterator.hasNext()) 
{
        String keyStr = (String)keysIterator.next();
        String valueStr = preferencesJSON.getString(keyStr);
}
like image 70
Daniel Avatar answered Dec 11 '22 12:12

Daniel


You can't iterate through above JsonObject, but if it were like this

["Preferences":{"Pref1":"Juan", "Pref2":"JuanK"}]

you could have done like

JSONArray array = new JSONArray(dataInStringForm);

for (int i=0;i< array.length(); i++)
{
   JSONObject json = array.getJsonObject(i);

   System.out.println(json.getString("Pref1"));
   System.out.println(json.getString("Pref2"));
}
like image 30
Umer Farooq Avatar answered Dec 11 '22 11:12

Umer Farooq