代码之家  ›  专栏  ›  技术社区  ›  Mateva

如何使Jackson的序列化包含属性尊重JAXB“必需”属性?

  •  3
  • Mateva  · 技术社区  · 7 年前

    我使用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覆盖。包括NON\u NULL序列化策略(忽略NULL元素,不添加空标记)。

    @XmlElement(name = "some-value", required = true) 
    protected String someValue;
    

    有没有一种方法可以保持这种策略,但要尊重JAXB的required标志,并在每次没有值时都编写一个空元素?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Mateva    7 年前

    事实证明 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

    这是为了

    子类 JaxbAnnotationIntrospector ,重写方法 findPropertyInclusion()