如何让Gson反序列化接口类型? [英] How can I get Gson to deserialize an interface type?
本文介绍了如何让Gson反序列化接口类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个界面
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反序列化一个类,该类实现为
I want to deserialize a class using Gson which is implemented as
public class UVW {
ABC abcObject;
}
当我尝试像gson.fromJson(jsonString, UVW.class);
一样反序列化它时,它返回我null
. jsonString是UTF_8字符串.
when I try to deserialize it like gson.fromJson(jsonString, UVW.class);
it returns me null
. jsonString is UTF_8 String.
是因为在UVW类中使用了接口吗?如果是,我该如何反序列化此类?
Is it because of interface used in UVW class? If yes, how do I deserialize such class?
推荐答案
您需要告诉Gson在反序列化ABC
时使用XYZ
. 您可以使用TypeAdapterFactory
.
You need to tell Gson to use XYZ
when it deserializes ABC
. You can do this using a 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);
}
}
这是一个完整的工作测试工具,说明了此示例:
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());
}
}
输出:
{"something":{"test":"hello"}}
class gson.TypeAdapterFactoryExample$XYZ
这篇关于如何让Gson反序列化接口类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文