将Jackson与Map <string,serializable =“”>

时间:2018-11-13 17:17:50

标签: java json jackson

我想知道是否可以通过某种方式正确进行以下反序列化:

public class MyClass {
     Map<String, Serializable> map;
     OtherObject object;
     [...]
}

ObjectMapper mapper = new ObjectMapper();
MyClass instance = mapper.readValue(someJson, MyClass);

当前,我正在尝试并遇到异常

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.io.Serializable: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

2 个答案:

答案 0 :(得分:0)

您可以将数据类的Map属性声明更改为不引用Serializable:

public class MyClass {
     Map<String, ?> map;
     OtherObject object;
     [...]
}

这也会影响地图的getter和setter的签名。但是,这确实松开了类型检查,并且映射的值可以是Object的任何子类,而不是Serializable的实现。如果这是重要的细节,则可以对地图值进行序列化后验证。

或者您可以配置自定义反序列化程序,如问题注释中所建议的那样。只需要将代码添加到哪里就可以了,这取决于这种情况在您的应用程序中的普及程度。

答案 1 :(得分:0)

从v2.10.0开始,Jackson支持对'Serializable'值进行简单的反序列化,即它将'Serializable'与'Object'相同。 有关更多详细信息,请参见此Github issue

因此将Jackson升级到2.10.0+并尝试。

相关问题