问题
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?
回答1:
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
回答2:
Thank you three-cups for the solution!
The same thing with generic type in case it's needed for multiple types:
public class SingleElementToListDeserializer<T> implements JsonDeserializer<List<T>> {
private final Class<T> clazz;
public SingleElementToListDeserializer(Class<T> clazz) {
this.clazz = clazz;
}
public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<T> resultList = new ArrayList<>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
resultList.add(context.<T>deserialize(e, clazz));
}
} else if (json.isJsonObject()) {
resultList.add(context.<T>deserialize(json, clazz));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return resultList;
}
}
And configuring Gson:
Type myOtherClassListType = new TypeToken<List<MyOtherClass>>() {}.getType();
SingleElementToListDeserializer<MyOtherClass> adapter = new SingleElementToListDeserializer<>(MyOtherClass.class);
Gson gson = new GsonBuilder()
.registerTypeAdapter(myOtherClassListType, adapter)
.create();
回答3:
Building off three-cups answer, I have the following which lets the JsonArray be deserialized directly as an array.
static public <T> T[] fromJsonAsArray(Gson gson, JsonElement json, Class<T> tClass, Class<T[]> tArrClass)
throws JsonParseException {
T[] arr;
if(json.isJsonObject()){
//noinspection unchecked
arr = (T[]) Array.newInstance(tClass, 1);
arr[0] = gson.fromJson(json, tClass);
}else if(json.isJsonArray()){
arr = gson.fromJson(json, tArrClass);
}else{
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return arr;
}
Usage:
String response = ".......";
JsonParser p = new JsonParser();
JsonElement json = p.parse(response);
Gson gson = new Gson();
MyQuote[] quotes = GsonUtils.fromJsonAsArray(gson, json, MyQuote.class, MyQuote[].class);
来源:https://stackoverflow.com/questions/7668507/gson-handle-object-or-array