I've got the following classes
public class MyClass { private List<MyOtherClass> others; } public class MyOtherClass { private String name; }
And I have JSON that may look like this
{ others: { name: "val" } }
or this
{ others: [ { name: "val" }, { name: "val" } ] }
I'd like to be able to use the same MyClass
for both of these JSON formats. Is there a way to do this with Gson?
I came up with an answer.
private static class MyOtherClassTypeAdapter implements JsonDeserializer<List<MyOtherClass>> { public List<MyOtherClass> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) { List<MyOtherClass> vals = new ArrayList<MyOtherClass>(); if (json.isJsonArray()) { for (JsonElement e : json.getAsJsonArray()) { vals.add((MyOtherClass) ctx.deserialize(e, MyOtherClass.class)); } } else if (json.isJsonObject()) { vals.add((MyOtherClass) ctx.deserialize(json, MyOtherClass.class)); } else { throw new RuntimeException("Unexpected JSON type: " + json.getClass()); } return vals; } }
Instantiate a Gson object like this
Type myOtherClassListType = new TypeToken<List<MyOtherClass>>() {}.getType(); Gson gson = new GsonBuilder() .registerTypeAdapter(myOtherClassListType, new MyOtherClassTypeAdapter()) .create();
That TypeToken
is a com.google.gson.reflect.TypeToken
.
You can read about the solution here:
https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener
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