简体   繁体   中英

Converting XML String to Java Object Jackson / JAXB

First time posting on stackoverflow other than looking for some help!

I've got a blob of XML that I am trying to deserialize into a simple Java Object.

I have the following blob of XML:

<library>
    <book index="654" name="Harry Potter" price="£11.99" rating="5"/>
    <book index="7893" name="Ready Player One" price="£16.99" rating="5"/>
    <book index="433" name="Piers Morgan; Don't You Know Who I Am?" price="£8.99" rating="2"/>
</library>

I am then trying to convert that into a simple POJO:

@JacksonXmlRootElement(localName = "library")
public class Library {
    //This will be the breaking point :'(
    List<Book> bookList = new ArrayList<>();
}

public class Book {
    @JacksonXmlProperty(isAttribute = true)
    Integer index;

    @JacksonXmlProperty(isAttribute = true)
    String name;

    @JacksonXmlProperty(isAttribute = true)
    String price;

    @JacksonXmlProperty(isAttribute = true)
    Integer rating;
}

I am struggling to find the right annotations to use in Jacksons documentation. I'm sure this must be a really simple change, as it normally is!

I opted for Jackson over JAXB as Jackson is newer library, and I'm aware of some speed issues associated with JAXB.

No matter how hard I try here I keep getting stuck the books list is coming back with no entries. Can anyone help? Would anyone recommend I take a look at JAXB over Jackson?

As you expected, you only need some annotations on your List<Book> property, to make the Jackson deserialization work correctly with your XML contents:

  • You need @JacksonXmlProperty with isAttribute = false (to tell Jackson you have <book> elements, but not book = "...." attributes) and localName = "book" (to tell Jackson the name of these elements)
  • You need @JacksonXmlElementWrapper with useWrapping = false (to tell Jackson you don't have an additional wrapper element around these <book> elements)
  • And by the way: You don't need to initialize it with = new ArrayList<>() , because the Jackson deserialization will care for that, too.
@JacksonXmlProperty(isAttribute = false, localName = "book")
@JacksonXmlElementWrapper(useWrapping = false)
List<Book> bookList;

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