【问题标题】:Using Jackson to serialize xml using attributes without annotations使用Jackson使用不带注释的属性序列化xml
【发布时间】:2015-01-06 09:05:53
【问题描述】:

我目前正在编写一些代码,使用 Jackson 将遗留 POJO 序列化为 XML,但我需要使用属性而不是子元素对它们进行序列化。有没有办法在不向遗留类添加注释的情况下使用 Jackson 来做到这一点?

【问题讨论】:

    标签: java xml jackson


    【解决方案1】:

    有没有办法在不向遗留类添加注释的情况下使用 Jackson 来做到这一点?

    你可以尝试在jackson中使用Mix-in注解。通过这种方式,您可以保留遗留类,同时您将享受注释功能。这是如何做。

    Person.class

       class Person {
            private String username;
            private String lastName;
            private String address;
            private Integer age;
            //getters and setters 
    
        }
    

    Mixin.class

    abstract class Mixin{
    @JacksonXmlProperty(isAttribute = true)
        abstract String getUsername();
    
        @JacksonXmlProperty(isAttribute = true)
        abstract String getLastName();
    
        @JacksonXmlProperty(isAttribute = true)
        abstract String getAddress();
    
        @JacksonXmlProperty(isAttribute = true)
        abstract String getAge();
    
    }
    

    主要方法

    public static void main(String[] args) throws JsonProcessingException {
        Person p = new Person("Foo","Bar");
        p.setAddress("This address is too long");
        p.setAge(20);
    
        ObjectMapper xmlMapper = new XmlMapper();
    
        xmlMapper.addMixInAnnotations(Person.class, MixIn.class);
        String xml = xmlMapper.writeValueAsString(p);
        System.out.println(xml);
    }
    

    输出

    <Person xmlns="" username="Foo" lastName="Bar" address="This address is too long" age="20"></Person>
    

    【讨论】:

    • 是的!感谢您为使用 Mixin + Jackson XML Mapper 提供如此清晰的 + WORKING 示例
    猜你喜欢
    • 2014-11-11
    • 2020-04-11
    • 2020-08-01
    • 2011-12-07
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2018-04-04
    相关资源
    最近更新 更多