0

I'm currently working on an Android application that gets a JSON response from a website called CloudMine. Their responses are typically in this format:

{
    "success": {
        "key1": { "field": "value1" },
        "key2": { "field1": "value1", "field2": "value2" }
    },
    "errors": {
        "key3": { "code": 404, "message": "Not Found" }
    }
}

I currently want to loop through all the objects in the "success" object so I can access the different fields in each object. However, I've only been taught how to use the JsonParser from the gson API. The closest I got was using the names() method on the success object but Eclipse yelled at me because the method is undefined for this type.

I appreciate all the help that anyone can give me.

Thanks!

Omar Hrynkiewicz
  • 502
  • 1
  • 8
  • 21
user2896865
  • 65
  • 1
  • 2
  • 7

2 Answers2

5

This worked for me:

JsonObject myJsonObject = new Gson().fromJson(myJsonString, JsonObject.class);

            for (Map.Entry<String, JsonElement> entry : myJsonObject.entrySet()) {

                JsonObject entryObj = entry.getValue().getAsJsonObject();
            }

Based on the accepted answer to this question, although I've altered it for my use case:

Iterate over JsonObject properties

Claytronicon
  • 1,437
  • 13
  • 14
-1

Here's a very simple code that would iterate over objects in 'success':

JSONObject json = new JSONObject(responseString);
JSONObject success = json.getJSONObject("success");
JSONObject one;
for(Iterator it=success.keys(); it.hasNext(); ) {
    one = success.getJSONObject((String)it.next());
    //deal with the next object inside your 'success'
}
Aleks G
  • 56,435
  • 29
  • 168
  • 265