17

I have the following XML schema:

<Courses semester="1">
    <Course code="A231" credits="3">Intermediate A</Course>
    <Course code="A105" credits="2">Intro to A</Course>
    <Course code="B358" credits="4">Advanced B</Course>
</Courses>

I need to convert this into POJO as:

public class Schedule
{
   public int semester;
   public Course[] courses;
}

public class Course
{
   public String code;
   public int credits;
   public String name;
}

There are two important things to note here:

  1. The courses object are not wrapped in a tag
  2. Some of the properties are attributes

How do I need to annotate my objects to get FasterXML to deserialize this xml?

StaxMan
  • 113,358
  • 34
  • 211
  • 239
sbenderli
  • 3,654
  • 9
  • 35
  • 48

1 Answers1

23

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]]]
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • Unfortunately `@JacksonXmlText` is no more available on most recent jackson library if I am not wrong. Do you know how to proceed? – Stefano Scarpanti Aug 04 '20 at 14:46
  • 1
    @StefanoScarpanti, in JavaDoc for version [2.11](http://fasterxml.github.io/jackson-dataformat-xml/javadoc/2.11/com/fasterxml/jackson/dataformat/xml/annotation/JacksonXmlText.html) it is still available. Also [main project page](https://github.com/FasterXML/jackson-dataformat-xml) describes how it works so it should be there. Which version do you use? – Michał Ziober Aug 04 '20 at 14:52
  • 1
    Ok, you are right, I forced in my pom 2.9.6 jackson release and I can use those annotations. Thanks. – Stefano Scarpanti Aug 04 '20 at 15:55