我试图使用Jackson 2序列化地图,默认的ObjectMapper()给出了类似的内容:
{" {http://google.com/} MYNAME":" myvalue的"}
它可能使用QName.toString()方法来序列化qname键。
我尝试过为QName注册一个自定义序列化程序,但它没有被调用。
public static class QnameSerializer extends JsonSerializer<QName> {
@Override
public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
jgen.writeString(value.getLocalPart());
}
}
public static void main(String[] args) throws JsonProcessingException {
SimpleModule module = new SimpleModule();
module.addKeySerializer(QName.class, new QnameSerializer());
// tried module.addSerializer(QName.class, new QnameSerializer()) also
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
Map<QName, String> m =ImmutableMap.of(new QName("http://google.com/","myName","pre"), "myValue");
System.out.println(mapper.writeValueAsString(m));
}
我错过了什么吗?
答案 0 :(得分:0)
杰克逊需要在运行时知道通用映射类型,以找出密钥应该由自定义序列化程序序列化。您应该在创建编写器时使用the type reference,如下所示:
public class JacksonQName {
public static class QnameSerializer extends JsonSerializer<QName> {
@Override
public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider)
throws IOException {
System.out.println("QName serializer works");
jgen.writeFieldName(value.getLocalPart());
}
}
public static void main(String[] args) throws JsonProcessingException {
SimpleModule module = new SimpleModule();
module.addKeySerializer(QName.class, new QnameSerializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
Map<QName, String> m = ImmutableMap.of(
new QName("http://google.com/", "myName", "pre"),
"myValue");
TypeReference<Map<QName, String>> type = new TypeReference<Map<QName, String>>() {};
System.out.println(mapper.writerWithType(type).writeValueAsString(m));
}
}
输出:
QName serializer works
{"myName":"myValue"}