From POJO to XML and Back with JAXB and Java 11+

Java Architecture for XML Binding (JAXB) API was deprecated in Java 9 and with the JEP 320: Remove the Java EE and CORBA Modules removed from Java SE 11.

At the same time the JAXB module was rebranded to Jakarta XML Binding: and maintained as Java EE / Jakarta EE API and implementation.

Starting with Java 11+, you will have to add the JAXB API, as well as, the JAXB implementation as additional dependencies:

<?xml version="1.0" encoding="UTF-8"?>

Now a Java POJO:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

public class Duke {

    private String language;
    private int age;

    public Duke() {}

    public Duke(String language, int age) {
        this.language = language;
        this.age = age;

...can be serialized and deserialized:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class DukeTest {

    private JAXBContext context;

    public void init() throws JAXBException {
        this.context = JAXBContext.newInstance(Duke.class);


    public void serialization() throws JAXBException {
        Marshaller marshaller = this.context.createMarshaller();
        marshaller.marshal(new Duke("java", 2), new File("duke.xml"));

        Unmarshaller unmarshaller = this.context.createUnmarshaller();
        Object unmarshalled = unmarshaller.unmarshal(new File("duke.xml"));

...into XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

See the serialization in action in a 5 minutes screencast: With POJOs To XML And Back With JAXB


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments