Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson handle object or array

Tags:

gson

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?

like image 400
three-cups Avatar asked Oct 05 '11 22:10

three-cups


1 Answers

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

like image 96
three-cups Avatar answered Oct 11 '22 01:10

three-cups