The code example uses the following Java class:
@XmlRootElement()
public class Recipe {
private String title;
private int duration;
public String getTitle() {
return title;
}
@XmlTransient
public void setTitle(String title) {
this.title = title;
}
public int getDuration() {
return duration;
}
@XmlElement
public void setDuration(int duration) {
this.duration = duration;
}
}
The following code performs the marshalling / unmarshalling:
Recipe recipe = new Recipe();
recipe.setDuration(30);
recipe.setTitle("Chicken recipe");
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector
= new JaxbAnnotationIntrospector();
mapper.setAnnotationIntrospector(introspector);
// Printing JSON
String result = mapper.writeValueAsString(recipe);
System.out.println(result);
// Parsing JSON
Recipe retr = mapper.readValue(result, Recipe.class);
System.out.println("Title : " + retr.getTitle());
System.out.println("Duration: " + retr.getDuration());
<dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>2.0.5</version> </dependency>
{"duration":30}
Title : null
Duration: 30
Pojo to XML • Pojo to JSON • JAXB to XML • JAXB to JSON • JAXB Annotations Tutorial Table Of Content