Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Gson handle object or array

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...