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