Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jackson to serialize xml using attributes without annotations

Tags:

java

xml

jackson

I am currently writing some code using Jackson to serialize legacy POJOs into XML, but I need them to be serialized using attributes not child elements. Is there a way to do this using Jackson without adding annotations to the legacy classes?

like image 456
user439407 Avatar asked Dec 10 '25 07:12

user439407


1 Answers

Is there a way to do this using Jackson without adding annotations to the legacy classes?

You can try to use Mix-in annotations in jackson. In this way you can preserve your legacy classes and the same time you will enjoy the annotations feature. Here's how.

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();

}

Main method

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);
}

Output

<Person xmlns="" username="Foo" lastName="Bar" address="This address is too long" age="20"></Person>
like image 113
Ken de Guzman Avatar answered Dec 11 '25 20:12

Ken de Guzman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!