我正在使用Jackson来支持Jackson和JAXB注释,并将对象序列化为XML。
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.registerModule(new JacksonXmlModule());
xmlMapper.registerModule(new JaxbAnnotationModule());
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
或者,我尝试配置具有相同结果的AnnotationIntrospector
。
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setAnnotationIntrospector(
new AnnotationIntrospectorPair(new XmlJaxbAnnotationIntrospector(), new JacksonAnnotationIntrospector()));
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
但是,使用 JAXB XmlEmelemt' required 属性注释的 POJO 字段将被忽略,因为该标志被JsonInclude.Include.NON_NULL序列化策略覆盖(忽略空元素,不添加空标记(。
@XmlElement(name = "some-value", required = true)
protected String someValue;
有没有办法保留这个策略,但尊重JAXB的要求标志,并在每次没有价值时写一个空元素?
事实证明required
仅在解组时使用,并且上述行为是规范的。
无论如何,对我有用的是:
选项 1
再添加一个自定义JsonSerializer
。对于特定的必需元素(它是另一个元素的组成部分的一部分,比如ObjectType
(,我只是在null
时将值设置为空字符串并将其写掉:
public void serialize(ObjectType obj, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeStartObject();
// write other elements
String someValue = obj.getSomeValue();
if (someValue == null) {
someValue = "";
}
gen.writeStringField("some-value", someValue);
gen.writeEndObject();
}
选项 2
这是fasterxml
船员在讨论后提出的 https://github.com/FasterXML/jackson-module-jaxb-annotations/issues/68#issuecomment-355055658
这是
子类
JaxbAnnotationIntrospector
,覆盖方法findPropertyInclusion()