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:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.moxy</artifactId>
<version>2.6.0</version>
</dependency>
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:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Now an ordinary JAXB POJO:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Workshop {
private String title;
private String description;
public Workshop() {
}
public Workshop(String title, String description) {
this.title = title;
this.description = description;
}
@Override
public int hashCode() {
//...
}
@Override
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;
@Before
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");
}
@Test
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