我有一个接口
public interace ABC {
}
实现如下:
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
}
}
我想使用Gson来反序列化一个类,它被实现为
public class UVW {
ABC abcObject;
}
当我试图像gson.fromJson(jsonString, UVW.class);
那样反序列化它时,它返回给我null
。jsonString是UTF_8 String.
是因为UVW类中使用的接口吗?如果是,我如何反序列化这样的类?
您需要告诉Gson在反序列化ABC
时使用XYZ
。您可以使用TypeAdapterFactory
。
短暂,因此:
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);
}
}
下面是一个完整的工作测试工具,说明了这个例子:
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());
}
}
输出:{"something":{"test":"hello"}}
class gson.TypeAdapterFactoryExample$XYZ