JAXB JSON POJO Serialization Example

To serialize a POJO into JSON using JAXB you will have to use a custom JAXB runtime like e.g. EclipseLink MOXy:


According to the discovery process, you will have to put a jaxb.properties file in the same package as your model classes (e.g. src/main/resources/com/airhacks) with the following content:


Now an ordinary JAXB POJO:

public class Workshop {

    private String title;
    private String description;

    public Workshop() {

    public Workshop(String title, String description) {
        this.title = title;
        this.description = description;

    public int hashCode() {

    public boolean equals(Object obj) {


Can be serialized / deserialized without any additional ceremony:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import ...

public class WorkshopIT {

    private JAXBContext jaxbContext;
    private Unmarshaller unmarshaller;
    private Marshaller marshaller;

    public void init() throws JAXBException {
        this.jaxbContext = JAXBContext.newInstance(Workshop.class);
        this.marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty("eclipselink.media-type", "application/json");
        this.unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setProperty("eclipselink.media-type", "application/json");

    public void serialize() throws JAXBException {
        Workshop origin = new Workshop("java ee", "rocking platform");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        this.marshaller.marshal(origin, baos);

        byte[] content = baos.toByteArray();
        System.out.println(new String(content));

        ByteArrayInputStream bais = new ByteArrayInputStream(content);
        Workshop copy = (Workshop) this.unmarshaller.unmarshal(bais);

        assertNotSame(origin, copy);
        assertEquals(origin, copy);


See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


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