如果我尝试反序列化下面的 Wrapper
类,它旨在保存类 HashMap
的实例,反序列化器将替换 com.google.gson 的类。 internal.LinkedTreeMap
,这是不需要的。
我如何确保字段的实际类型是我想要的,即 HashMap
?
这是一个 MCVE 来说明我在问什么:
public class HashMapTry {
public static class Wrapper {
public String title = "My Title";
public Map<String, String> map = new HashMap<String,String>();
}
public static void main(String[] args) {
Wrapper wrapper = new Wrapper();
Wrapper wrapper2;
wrapper.map.put("vertical", "1, 0");
wrapper.map.put("horizontal", "0, 1");
GsonBuilder gb = new GsonBuilder()
.enableComplexMapKeySerialization()
.serializeNulls()
.setPrettyPrinting()
.setVersion(1.0)
.setDateFormat("yyyy.MM.dd HH:mm:ss");
Gson g = gb.create();
String json = g.toJson(wrapper);
System.out.println(json);
wrapper2 = g.fromJson(json, Wrapper.class);
System.out.println(wrapper2.map.getClass());
}
}
输出:
{
"title": "My Title",
"map": {
"horizontal": "0, 1",
"vertical": "1, 0"
}
}
class com.google.gson.internal.LinkedTreeMap
最佳答案
只需在 Wrapper 类中将其声明为 HashMap
即可。 Gson 不喜欢默认 反序列化到接口(interface),因为它必须弄清楚要反序列化到哪个类。如果它是一些随机接口(interface)(例如 interface MyInterface
),它实际上会导致问题,因为该接口(interface)没有默认行为,您必须指定它,您可以通过注册 TypeAdapter
来实现.
但是,对于这种情况来说,这太复杂了。只需在包装类中将其称为 HashMap
即可。 只有在实现无关紧要时才针对接口(interface)进行编程,但如果它确实重要则针对实现进行编程,这里的情况很明显。
public static class Wrapper {
public String title = "My Title";
public HashMap<String, String> map = new HashMap<String, String>();
}
输出:
{
"title": "My Title",
"map": {
"horizontal": "0, 1",
"vertical": "1, 0"
}
}
class java.util.HashMap
关于java - Gson 如何将接口(interface)反序列化为特定实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181417/