在以前的案例中,我使用了Jackson(由Codehaus托管的Jackson 1.9)多态序列化将格式List<MyBaseType>
的列表序列化为适当的对象类型。
现在,我需要序列化Map<String,MyBaseType>
并对其进行反序列化。我看到当写入值时,我得到了我期望的正确格式:
{"className":"IndexRecord","id":0,"fields":{"className":"FieldMap","df12":{"className":"CustomStringType","value":"ralph"}}}
我尝试了一些事情,包括地图的包装器实现(FieldMap
)。每当我尝试反序列化时,我都会
Could not resolve type id 'CustomStringType' into a subtype of 'MyBaseType'
我确实已正确注释了所有内容,包括JsonTypeInfo
和JsonSubType
这是一个非常简单的案例来实现它。假设你有这些POJO
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className")
@JsonIgnoreProperties(ignoreUnknown = true)
public class IndexRecord {
private int id;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className")
private Map<String,IndexValue> fields;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeName("IndexValue")
public class IndexValue {
private String value;
}
当我运行以下测试工具时:
IndexRecord indexRecord = new IndexRecord();
IndexValue iv = new IndexValue();
iv.setValue("ralph");
indexRecord.getFields().put("foo",iv);
ObjectMapper om = new ObjectMapper();
String data = om.writeValueAsString(indexRecord);
System.out.println("Data is "+data);
IndexRecord result = om.readValue(data,IndexRecord.class);
根据一些文档,看起来我可能需要实现自定义反序列化器。