The following is a simple Java object with JAXB annotation:
@XmlRootElement public class Book { private String title; private int year; public String getTitle() { return title; } @XmlElement public void setTitle(String title) { this.title = title; } public int getYear() { return year; } @XmlElement public void setYear(int year) { this.year = year; } }
public static void main(String[] args) throws JAXBException { Book book = new Book(); book.setTitle("Book title"); book.setYear(2010); // Creating a Marshaller JAXBContext jaxbContext = JAXBContext.newInstance(Book.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter result = new StringWriter(); jaxbMarshaller.marshal(book, result); // Printing XML String xml = result.toString(); System.out.println(xml); // Creating an Unmarshaller Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); StringReader sr = new StringReader(xml); Book retr = (Book) jaxbUnmarshaller.unmarshal(sr); System.out.println("Title: " + retr.getTitle()); System.out.println("Year : " + retr.getYear()); }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <book> <title>Book title</title> <year>2010</year> </book> Title: Book title Year : 2010
Pojo to XML • Pojo to JSON • JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content
Hello,
ReplyDeleteNice article. One thing to note is that since JAXB (JSR-222) is configuration by exception. This means you only need to add annotations where you want the XML representation to be different from the default. Your example would work the same way if you removed the two @XmlElement annotations.
- JAXB - No Annotations Required
-Blaise
Thanks Blaise.
Delete