我有一个嵌套的
Map<StructureNode, Map<String, String>>
,需要自定义键序列化器和反序列化器(StructureNode
包含对其他对象的引用,这些对象需要作为此映射的键)。我使用了以下方法:
Jackson Modules for Map Serialization
得到以下结果。 自定义序列化器:public class StructureNodeKeySerializer extends JsonSerializer<StructureNode> {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public void serialize(StructureNode value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
StringWriter writer = new StringWriter();
mapper.writeValue(writer, value.copyUpwards());
gen.writeFieldName(writer.toString());
}
}
自定义反序列化器:
public class StructureNodeKeyDeserializer extends KeyDeserializer {
private static final ObjectMapper mapper = new ObjectMapper();
@Override
public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException {
return mapper.readValue(key, StructureNode.class);
}
}
使用方法:
@JsonDeserialize(keyUsing = StructureNodeKeyDeserializer.class) @JsonSerialize(keyUsing = StructureNodeKeySerializer.class)
private Map<StructureNode, String> structureIds;
@JsonDeserialize(keyUsing = StructureNodeKeyDeserializer.class) @JsonSerialize(keyUsing = StructureNodeKeySerializer.class)
private Map<StructureNode, Map<String, String>> metadata;
这段代码可以正确地序列化一个 Map<StructureNode, String>
,但如果应用于一个嵌套的 Map<StructureNode, Map<String, String>>
,则会出现以下错误:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: java.lang.String cannot be cast to structure.StructureNode
Jackson似乎正在使用相同的自定义序列化方法来处理"子映射"。是否有一种好的方法可以解决这个问题,而不是用另一个自定义(非Map
)对象替换"子映射"?
ObjectMapper
。 - teppic