Axarydax
Axarydax

Reputation: 16603

Get element name with GSON

I have JSON like this:

{"foos":[{"id":1}, {"id":2}]}

I can turn it into List<Foo> pretty simply with GSON, like this:

Type t = new TypeToken<List<Foo>>(){}.getType();
JsonObject resp = new Gson().fromJson(
    new JsonParser().parse(json).getAsJsonObject().get("foos",t);

But let's assume that I also have another JSON, where the name of the array and type changes

{"bars":[{"id":3},{"id":9}]}

Of course I could just swap the "foos" parameter for "bars", but if it's possible, I'd like my software to do it for me.

Is there a way to extract the name of the array child with the GSON library?

Upvotes: 1

Views: 3452

Answers (2)

MikO
MikO

Reputation: 18741

Looking at your JSON examples, I assume that the name of the list element can change, but not the content of the list. If this is correct, you could parse your JSON response just like this:

Type mapType = new TypeToken<Map<String, List<Foo>>>() {}.getType();
Map<String, List<Foo>> map = gson.fromJson(jsonString, mapType);

And then you can access the name of the list with:

String listName = map.keySet().iterator().next();

If the content of the list could also change, things get a bit more complicated...

Upvotes: 1

cyber_rookie
cyber_rookie

Reputation: 665

I'm not sure if I understood what you want correctly, but aren't you referring to the use of generics? I mean you could write a method that returns you a List of your relevant class? Something along the lines of

Type type = new TypeToken<List<MyClass>>() {}.getType();
List<MyClass> myObjects = getMyObjects(new JsonParser().parse(json).getAsJsonObject().get("foos"), type);

public static List<T> getMyObjects(String jsonString, Type type) {
    Gson gson = new Gson();
    List<T> myList = gson.fromJson(jsonString, type);

    return myList;
}

Upvotes: 3

Related Questions