我正在使用 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 的必需属性注释的 POJO 字段将被忽略,因为该标志被 JsonInclude.Include.NON_NULL 序列化策略覆盖(忽略空元素并且不添加空标记)。
@XmlElement(name = "some-value", required = true)
protected String someValue;
有没有办法保持这种策略,但尊重 JAXB 的 required 标志并在每次没有值时写入一个空元素?
最佳答案
原来 required
仅在解码时使用,上面的行为是 by specification .
无论如何,对我有用的是:
选项 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
这是为了
sub-class
JaxbAnnotationIntrospector
, override methodfindPropertyInclusion()
关于java - 如何使 Jackson 的序列化包含属性尊重 JAXB "required"属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48063070/