Sunday, 5 August 2012

JAXB JSON Marshalling / Unmarshalling

The Jackson library offers a library to process objects with JAXB annotations, but it Jackson does not support all JAXB annotations (see the bottom of this page for more information).

The code example uses the following Java class:
public class Recipe {

    private String title;
    private int duration;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

    public int getDuration() {
        return duration;

    public void setDuration(int duration) {
        this.duration = duration;

We deliberately annotate the title as transient to prove that Jackson processes JAXB annotations and does not rely on the standard Pojo to JSON processus.

The following code performs the marshalling / unmarshalling:
Recipe recipe = new Recipe();
recipe.setTitle("Chicken recipe");
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector
    = new JaxbAnnotationIntrospector();
// Printing JSON
String result = mapper.writeValueAsString(recipe);
// Parsing JSON
Recipe retr = mapper.readValue(result, Recipe.class);
System.out.println("Title   : " + retr.getTitle());
System.out.println("Duration: " + retr.getDuration());
It relies on the following dependency:
And produces the following:
Title   : null
Duration: 30

Pojo to XMLPojo to JSONJAXB to XMLJAXB to JSON • JAXB Annotations Tutorial Table Of Content