Search code examples
javaxmlserializationjacksonjackson-dataformat-xml

Java+Jackson+XML: serialize a java object properties as XML elements with same names


I have a Java object and I would like to serialize it into XML using Jackson library:

public class Point {
    private Integer x;
    private Integer y;
    //getters/setters
}

and I would like to serialize it into following format:

<point>
    <property name="x" value="1" />
    <property name="y" value="1" />
</point>

instead of what I get using Jacskon:

<point>
    <x>1</x>
    <y>1</y>
</point>

I do not want to change the Point object properties or structure. Is there a way to serialize the Point object into required format using a Jackson annotations or custom serializer? If yes then how do I do that?

I am using Jackson library:

public class Serializer {
    XmlMapper mapper = new XmlMapper();

    public void serialize(File file, Object object) throws IOException {
        mapper.writeValue(file, object);
    }

}

Solution

  • You need to mark those properties as attributes like this:

    public class Point {
    
        @JacksonXmlProperty(isAttribute = true)
        private Integer x;
        @JacksonXmlProperty(isAttribute = true)
        private Integer y;
        //getters/setters
    }