44

I would like to iterate through the big wrapping JsonObject with Gson. My final aim is to get an ArrayList of all existing three digit code integers in the inner "unterfeld" objects, but that will be no problem once I can iterate through the outer object's properties.

{
  "something1": {
    "bezeichnung": "something1",
    "unterfeld": [
      {
        "bezeichnung": "bla1",
        "unterregionen": [
        ],
        "code": 111
      },
      {
        "bezeichnung": "bla2",
        "unterregionen": [
        ],
        "code": 222
      }
    ],
    "code": 3
  },
  "something2": {
    "bezeichnung": "something2",
    "unterfeld": [
      {
        "bezeichnung": "bla3",
        "unterregionen": [
        ],
        "code": 333
      }
    ],
    "code": 6
  },
  "something3": {
    "bezeichnung": "something3",
    "unterfeld": [
      {
        "bezeichnung": "bla4",
        "unterregionen": [
        ],
        "code": 444
      },
      {
        "bezeichnung": "bla5",
        "unterregionen": [
        ],
        "code": 555
      },
      {
        "bezeichnung": "bla6",
        "unterregionen": [
        ],
        "code": 666
      }
    ],
    "code": 9
  }
}

Is there any neat way to do that?

David Harkness
  • 35,992
  • 10
  • 112
  • 134
dotwin
  • 1,302
  • 2
  • 11
  • 31

1 Answers1

87

You can use entrySet to iterate over the members of the outermost JsonObject.

JsonObject object;
ArrayList<Integer> codes = new ArrayList<Integer>();
for (Map.Entry<String,JsonElement> entry : object.entrySet()) {
    JsonArray array = entry.getValue().getAsJsonObject().getAsJsonArray("unterfeld");
    for (JsonElement codeHolder : array) {
        codes.add(codeHolder.getAsJsonObject().getAsJsonPrimitive("code").getAsInt());
    }
}
David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • 1
    Thanks a lot first of all. It is probably my lack of understanding of the Map object, but I get an error: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method getAsJsonArray(String) is undefined for the type Map.Entry – dotwin Apr 15 '12 at 19:29
  • I missed a call to `getValue` to pull the `JsonElement` from the `Map.Entry`. – David Harkness Apr 15 '12 at 19:32
  • 1
    At least with version 2.2.4 of GSON, to make it work you have to replace `JsonArray array = entry.getValue().getAsJsonArray("unterfeld");` with JsonArray array = entry.getValue().getAsJsonObject().get("unterfeld").getAsJsonArray(); – s0nica Feb 25 '14 at 16:08
  • @s0nica Quite right. I have fixed that error and others and checked that it compiles in Eclipse. – David Harkness Feb 25 '14 at 20:30