Jackson xml空元素序列化

时间:2013-11-21 16:06:31

标签: java xml serialization jackson

我很难用这个。 Jackson 2.2 XML序列化器似乎以这种方式序列化空对象字段:

<field/>

如何强制它序列化这样的空字段:

<field></field>

非常感谢您的时间和答案。

1 个答案:

答案 0 :(得分:1)

请看这个问题:How do you override the null serializer in Jackson 2.0?。对于XmlMapper,它可能如下所示。创建NullSerializer

class NullSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString("");
    }
}

简单用法:

XmlSerializerProvider provider = new XmlSerializerProvider(new XmlRootNameLookup());
provider.setNullValueSerializer(new NullSerializer());

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setSerializerProvider(provider);

System.out.println(xmlMapper.writeValueAsString(new Entity()));

以上程序打印:

<Entity xmlns=""><field></field></Entity>