简体   繁体   中英

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

}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM