我正在尝试反序列化这样的接口:
public interface MyCollection<T> extends List<T> {...}
MyCollection
有多种实现方式,例如public class MyBasicCollection<String>
和public class MyOtherCollection<String>
。
我已经在界面上添加了注释,如下所示:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = MyBasicCollection.class, name = "basic"),
@JsonSubTypes.Type(value = MyOtherCollection.class, name = "other")
})
public interface MyCollection<T> extends List<T> {...}
要序列化和反序列化的详细代码如下:
MyCollection<String> testCollection = new MyBasicCollection<String>();
ObjectMapper mapper = new ObjectMapper();
String serializedString = mapper.writeValueAsString(testCollection);
MyCollection<String> reconstructed = mapper.readValue(serializedString, new TypeReference<MyCollection<String>>(){});
我会得到
找不到非具体Collection类型的反序列化器
JsonMappingException。
但是,如果我将最后一行更改为
MyCollection<String> reconstructed = mapper.readValue(serializedString, new TypeReference<MyBasicCollection<String>>(){});
它运行完美。
有没有办法使反序列化与多态类型一起工作?