【问题标题】:Mixins and Jackson annotationsMixins 和 Jackson 注释
【发布时间】:2018-11-08 10:04:30
【问题描述】:

我们目前有一些用于数据对象的 mixin,以便将注释排除在数据对象之外。比如

public class SomeDataObj {
    private int a;

    public int getA() { return this.a; }

    public void setA(final int a) { this.a = a; }
}

public interface SomeDataObjMixin {
    @JacksonXmlElementWrapper(useWrapping = false)
    @JacksonXmlProperty(localName = "A")
    int getA();

    @JacksonXmlElementWrapper(useWrapping = false)
    @JacksonXmlProperty(localName = "A")
    void setA(int a);
}

然后在我们的对象映射器类中我们有

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class OurXmlMapper extends XmlMapper {


    public OurXmlMapper(final ConfigurableCaseStrategy caseStrategy) {
        setPropertyNamingStrategy(caseStrategy);
        setSerializationInclusion(Include.NON_NULL);

        //yadda yadda

        addMixin(SomeDataObj.class, SomeDataObjMixin.class);

        // etc etc

}

但是,出于各种原因,我想为数据对象中的私有字段添加一个新注释,而不是 getter 或 setter。有没有办法通过 mixin 来保持这种分离?我尝试创建一个基本类作为mixin(不是接口),并添加了私有字段 对此的新注释。这并没有实现我想要的。有什么想法吗?

【问题讨论】:

    标签: java jackson mixins


    【解决方案1】:

    使用 Concrete 类作为 mixin 工作。

    // ******************* Item class *******************
    public class Item {
    
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
    // ******************* ItemMixIn class *******************
    @JacksonXmlRootElement(localName = "item-class")
    public class ItemMixIn {
    
        @JacksonXmlProperty(localName = "firstName")
        private String name;
    
    }
    
    // ******************* test method *******************
    public void test() throws Exception {
    
        ObjectMapper mapper = new XmlMapper();
        mapper.addMixIn(Item.class, ItemMixIn.class);
    
        Item item = new Item();
        item.setName("hemant");
    
        String res = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(item);
        System.out.println(res);
    }
    

    输出:

    <item-class>
      <firstName>hemant</firstName>
    </item-class>
    

    我有杰克逊版本2.9.5

    【讨论】:

    • 谢谢。自从提出让我的问题无用的问题后,我意识到了一些事情。
    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多