How to deserialize XML with annotations using FasterXML How to deserialize XML with annotations using FasterXML xml xml

How to deserialize XML with annotations using FasterXML


You have to add jackson-dataformat-xml dependency to your project:

<dependency>    <groupId>com.fasterxml.jackson.dataformat</groupId>    <artifactId>jackson-dataformat-xml</artifactId>    <version>2.3.3</version></dependency>

After that you can use XML annotations in this way:

@JacksonXmlRootElement(localName = "Courses")class Schedule {    @JacksonXmlProperty(isAttribute = true)    private int semester;    @JacksonXmlProperty(localName = "Course")    private Course[] courses;    // getters, setters, toString, etc}class Course {    @JacksonXmlProperty(isAttribute = true)    private String code;    @JacksonXmlProperty(isAttribute = true)    private int credits;    @JacksonXmlText(value = true)    private String name;    // getters, setters, toString, etc}

Now, you have to use XmlMapper instead of ObjectMapper:

JacksonXmlModule module = new JacksonXmlModule();module.setDefaultUseWrapper(false);XmlMapper xmlMapper = new XmlMapper(module);System.out.println(xmlMapper.readValue(xml, Schedule.class));

Above script prints:

Schedule [semester=1, courses=[[code=A231, credits=3, name=Intermediate A], [code=A105, credits=2, name=Intro to A], [code=B358, credits=4, name=Advanced B]]]