问题
I have an interface
public interace ABC {
}
Implementation of this is as follows:
public class XYZ implements ABC {
private Map<String, String> mapValue;
public void setMapValue( Map<String, String> mapValue) {
this.mapValue = mapValue;
}
public Map<String, String> getMapValue() {
return this.mapValue
}
}
I want to deserialize a class using Gson which is implemented as
public class UVW {
ABC abcObject;
}
when I try to deserialize it like gson.fromJson(jsonString, UVW.class); it returns me null. jsonString is UTF_8 String.
Is it because of interface used in UVW class? If yes, how do I deserialize such class?
回答1:
You need to tell Gson to use XYZ when it deserializes ABC. You can do this using a TypeAdapterFactory.
Briefly, thus:
public class ABCAdapterFactory implements TypeAdapterFactory {
private final Class<? extends ABC> implementationClass;
public ABCAdapterFactory(Class<? extends ABC> implementationClass) {
this.implementationClass = implementationClass;
}
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ABC.class.equals(type.getRawType())) return null;
return (TypeAdapter<T>) gson.getAdapter(implementationClass);
}
}
Here is a complete working test harness that illustrates this example:
public class TypeAdapterFactoryExample {
public static interface ABC {
}
public static class XYZ implements ABC {
public String test = "hello";
}
public static class Foo {
ABC something;
}
public static void main(String... args) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new ABCAdapterFactory(XYZ.class));
Gson g = builder.create();
Foo foo = new Foo();
foo.something = new XYZ();
String json = g.toJson(foo);
System.out.println(json);
Foo f = g.fromJson(json, Foo.class);
System.out.println(f.something.getClass());
}
}
Output:
{"something":{"test":"hello"}}
class gson.TypeAdapterFactoryExample$XYZ
来源:https://stackoverflow.com/questions/31951779/how-can-i-get-gson-to-deserialize-an-interface-type