Serialization

serialization2JaxbDemo

Path
pkg20serialization/src/main/java/pkg20serialization/serialization2JaxbDemo.java
Package
pkg20serialization
Study order
2
Run
Maven module
Command
mvn -f pkg20serialization/pom.xml compile
Dependencies
jakarta.xml.bind.JAXBContext, jakarta.xml.bind.Marshaller, jakarta.xml.bind.Unmarshaller, jakarta.xml.bind.annotation.XmlRootElement

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg20serialization/src/main/java/pkg20serialization/serialization2JaxbDemo.java
1package pkg20serialization;2 3import jakarta.xml.bind.JAXBContext;4import jakarta.xml.bind.Marshaller;5import jakarta.xml.bind.Unmarshaller;6import jakarta.xml.bind.annotation.XmlRootElement;7 8/*9 * serialization2JaxbDemo.java — XML binding with JAXB (Jakarta XML Bind).10 */11public class serialization2JaxbDemo {12 13    @XmlRootElement(name = "book")14    static class Book {15        public String title;16        public String author;17        Book() {}18        Book(String title, String author) { this.title = title; this.author = author; }19    }20 21    public static void main(String[] args) throws Exception {22        JAXBContext ctx = JAXBContext.newInstance(Book.class);23        Marshaller marshaller = ctx.createMarshaller();24        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);25 26        Book book = new Book("Java Concurrency", "Goetz");27        java.io.StringWriter sw = new java.io.StringWriter();28        marshaller.marshal(book, sw);29        System.out.println("JAXB XML:\n" + sw);30 31        Unmarshaller unmarshaller = ctx.createUnmarshaller();32        Book parsed = (Book) unmarshaller.unmarshal(new java.io.StringReader(sw.toString()));33        System.out.println("Parsed title: " + parsed.title);34    }35}