English 中文(简体)
Jackson - Quick Guide
  • 时间:2024-12-22

Jackson Annotations - Quick Guide


Previous Page Next Page  

Jackson Annotations - @JsonAnyGetter

@JsonAnyGetter allows a getter method to return Map which is then used to seriapze the additional properties of JSON in the similar fashion as other properties.

Example without @JsonAnyGetter

import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester { 
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper(); 
      try{
         Student student = new Student(); 
         student.add("Name", "Mark"); 
         student.add("RollNo", "1"); 
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      } 
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student {
   private Map<String, String> properties; 
   pubpc Student(){ 
      properties = new HashMap<>(); 
   } 
   pubpc Map<String, String> getProperties(){ 
      return properties; 
   } 
   pubpc void add(String property, String value){ 
      properties.put(property, value); 
   } 
}

Output

{
   "properties" : {
      "RollNo" : "1",
      "Name" : "Mark"
   } 
}

Example with @JsonAnyGetter

import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 
import com.fasterxml.jackson.annotation.JsonAnyGetter; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try{
         Student student = new Student(); 
         student.add("Name", "Mark"); 
         student.add("RollNo", "1"); 
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) {
         e.printStackTrace();
      } 
   }
}
class Student {
   private Map<String, String> properties;
   pubpc Student(){
      properties = new HashMap<>();
   }
   @JsonAnyGetter
   pubpc Map<String, String> getProperties(){
      return properties;
   }
   pubpc void add(String property, String value){
      properties.put(property, value);
   }
}

Output

{
   "RollNo" : "1",
   "Name" : "Mark"
}

Jackson Annotations - @JsonGetter

@JsonGetter allows a specific method to be marked as getter method.

Example without @JsonGetter

import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student("Mark", 1);
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) {
         e.printStackTrace();
      }
   }
}
class Student {
   private String name;
   private int rollNo;
   pubpc Student(String name, int rollNo){
      this.name = name;
      this.rollNo = rollNo;
   }  
   pubpc String getStudentName(){
      return name;
   } 
   pubpc int getRollNo(){
      return rollNo;
   }
}

Output

{
   "studentName" : "Mark",
   "rollNo" : 1
} 

Example with @JsonGetter

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.annotation.JsonGetter; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){ 
      ObjectMapper mapper = new ObjectMapper(); 
      try {
         Student student = new Student("Mark", 1);    
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      } 
      catch (IOException e) { 
         e.printStackTrace();  
      }   
   }
}
class Student {
   private String name;
   private int rollNo;
   pubpc Student(String name, int rollNo){
      this.name = name;
      this.rollNo = rollNo;
   }
   @JsonGetter
   pubpc String getStudentName(){
      return name;
   }
   pubpc int getRollNo(){
      return rollNo;
   }
}

Output

{
   "name" : "Mark",
   "rollNo" : 1
} 

Jackson Annotations - @JsonPropertyOrder

@JsonPropertyOrder allows a specific order to be preserved while seriapzing a JSON object.

Example without @JsonPropertyOrder

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student("Mark", 1);
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) {
         e.printStackTrace();
      }
   }
}
class Student {
   private String name;
   private int rollNo;
   pubpc Student(String name, int rollNo) {
      this.name = name;
      this.rollNo = rollNo;
   }
   pubpc String getName(){
      return name;
   }
   pubpc int getRollNo(){
      return rollNo; 
   }
}

Output

{
   "name" : "Mark",
   "rollNo" : 1
} 

Example @JsonPropertyOrder

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student("Mark", 1);
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) {
         e.printStackTrace();
      }
   }
}
@JsonPropertyOrder({ "rollNo", "name" })
class Student {
   private String name; 
   private int rollNo; 
   pubpc Student(String name, int rollNo){ 
      this.name = name; 
      this.rollNo = rollNo; 
   }  
   pubpc String getName(){ 
      return name; 
   } 
   pubpc int getRollNo(){ 
      return rollNo; 
   }  
}

Output

{ 
   "name" : "Mark", 
   "rollNo" : 1 
} 

Jackson Annotations - @JsonRawValue

@JsonRawValue allows to seriapze a text without escaping or without any decoration.

Example without @JsonRawValue

import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student("Mark", 1, "{"attr":false}");    
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student { 
   private String name; 
   private int rollNo; 
   private String json;  
   pubpc Student(String name, int rollNo, String json){
      this.name = name; 
      this.rollNo = rollNo; 
      this.json = json; 
   }  
   pubpc String getName(){ 
      return name; 
   } 
   pubpc int getRollNo(){ 
      return rollNo; 
   } 
   pubpc String getJson(){ 
      return json; 
   }  
}

Output

{ 
   "name" : "Mark", 
   "rollNo" : 1, 
   "json" : {"attr":false} 
} 

Example with @JsonRawValue

import java.io.IOException; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.annotation.JsonRawValue; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper(); 
      try {
         Student student = new Student("Mark", 1, "{"attr":false}");    
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student { 
   private String name; 
   private int rollNo;
   @JsonRawValue  
   private String json;  
   pubpc Student(String name, int rollNo, String json) {
      this.name = name; 
      this.rollNo = rollNo; 
      this.json = json; 
   }  
   pubpc String getName(){ 
      return name; 
   } 
   pubpc int getRollNo(){ 
      return rollNo; 
   } 
   pubpc String getJson(){ 
      return json; 
   }  
} 

Output

{ 
   "name" : "Mark", 
   "rollNo" : 1, 
   "json" : {"attr":false} 
}

Jackson Annotations - @JsonValue

@JsonValue allows to seriapze an entire object using its single method.

Example @JsonValue

import java.io.IOException; 
import com.fasterxml.jackson.annotation.JsonValue; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper(); 
      try { 
         Student student = new Student("Mark", 1);    
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student {
   private String name;
   private int rollNo;
   pubpc Student(String name, int rollNo){
      this.name = name;
      this.rollNo = rollNo;
   }
   pubpc String getName(){
      return name;
   } 
   pubpc int getRollNo(){
      return rollNo;
   }
   @JsonValue
   pubpc String toString(){
      return "{ name : " + name + " }";
   }
}

Output

"{ name : Mark }" 

Jackson Annotations - @JsonRootName

@JsonRootName allows to have a root node specified over the JSON. We need to enable wrap root value as well.

Example @JsonRootName

import java.io.IOException; 
import com.fasterxml.jackson.annotation.JsonRootName; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.SeriapzationFeature; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){ 
      ObjectMapper mapper = new ObjectMapper(); 
      try {
         Student student = new Student("Mark", 1);  
         mapper.enable(SeriapzationFeature.WRAP_ROOT_VALUE); 
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
@JsonRootName(value = "student") 
class Student {
   private String name; 
   private int rollNo; 
   pubpc Student(String name, int rollNo){ 
      this.name = name; 
      this.rollNo = rollNo; 
   }  
   pubpc String getName(){ 
      return name; 
   } 
   pubpc int getRollNo(){ 
      return rollNo; 
   }  
}

Output

{ 
   "student" : { 
      "name" : "Mark", 
      "rollNo" : 1 
   } 
}

Jackson Annotations - @JsonSeriapze

@JsonSeriapze is used to specify custom seriapzer to marshall the json object.

Example with @JsonSeriapze

import java.io.IOException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

import com.fasterxml.jackson.core.JsonGenerator; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.SeriapzerProvider; 
import com.fasterxml.jackson.databind.annotation.JsonSeriapze; 
import com.fasterxml.jackson.databind.ser.std.StdSeriapzer; 

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws ParseException {
      ObjectMapper mapper = new ObjectMapper(); 
      SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); 
      try {
         Student student = new Student("Mark", 1, dateFormat.parse("20-11-1984")); 
         String jsonString = mapper 
            .writerWithDefaultPrettyPrinter() 
            .writeValueAsString(student); 
         System.out.println(jsonString); 
      } 
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student {
   private String name; 
   private int rollNo; 
   @JsonSeriapze(using = CustomDateSeriapzer.class) 
   private Date dateOfBirth; 
   pubpc Student(String name, int rollNo, Date dob){ 
      this.name = name; 
      this.rollNo = rollNo; 
      this.dateOfBirth = dob; 
   }
   pubpc String getName(){
      return name;
   }
   pubpc int getRollNo(){
      return rollNo; 
   }
   pubpc Date getDateOfBirth(){ 
      return dateOfBirth; 
   }
}
class CustomDateSeriapzer extends StdSeriapzer<Date> {
   private static final long serialVersionUID = 1L; 
   private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
   pubpc CustomDateSeriapzer() { 
      this(null); 
   } 
   pubpc CustomDateSeriapzer(Class<Date> t) { 
      super(t); 
   } 
   @Override 
   pubpc void seriapze(Date value, 
      JsonGenerator generator, SeriapzerProvider arg2) throws IOException { 
      generator.writeString(formatter.format(value)); 
   } 
}

Output

{
   "name" : "Mark",
   "rollNo" : 1,
   "dateOfBirth" : "20-11-1984"
}

Jackson Annotations - @JsonCreator

@JsonCreator is used to fine tune the constructor or factory method used in deseriapzation. We ll be using @JsonProperty as well to achieve the same. In the example below, we are matching an json with different format to our class by defining the required property names.

Example @JsonCreator

import java.io.IOException; 
import java.text.ParseException; 

import com.fasterxml.jackson.annotation.JsonCreator; 
import com.fasterxml.jackson.annotation.JsonProperty; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws ParseException{ 
      String json = "{"id":1,"theName":"Mark"}"; 
      ObjectMapper mapper = new ObjectMapper();    
      try {
         Student student = mapper 
            .readerFor(Student.class) 
            .readValue(json); 
         System.out.println(student.rollNo +", " + student.name); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }
   }
}
class Student {
   pubpc String name; 
   pubpc int rollNo; 

   @JsonCreator 
   pubpc Student(@JsonProperty("theName") String name, @JsonProperty("id") int rollNo){
      this.name = name; 
      this.rollNo = rollNo; 
   }
}

Output

1, Mark 

Jackson Annotations - @JacksonInject

@JacksonInject is used when a property value is to be injected instead of being parsed from Json input. In the example below, we are inserting a value into object instead of parsing from the Json.

Example @JacksonInject

import java.io.IOException; 
import java.text.ParseException; 

import com.fasterxml.jackson.annotation.JacksonInject; 
import com.fasterxml.jackson.databind.InjectableValues; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws ParseException{ 
      String json = "{"name":"Mark"}"; 
      InjectableValues injectableValues = new InjectableValues.Std() 
         .addValue(int.class, 1); 
      
      ObjectMapper mapper = new ObjectMapper();    
      try {
         Student student = mapper 
            .reader(injectableValues) 
            .forType(Student.class) 
            .readValue(json); 
         System.out.println(student.rollNo +", " + student.name); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student {
   pubpc String name; 
   @JacksonInject 
   pubpc int rollNo;  
}

Output

1, Mark 

Jackson Annotations - @JsonAnySetter

@JsonAnySetter allows a setter method to use Map which is then used to deseriapze the additional properties of JSON in the similar fashion as other properties.

Example @JsonAnySetter

import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map; 

import com.fasterxml.jackson.annotation.JsonAnySetter; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){ 
      ObjectMapper mapper = new ObjectMapper(); 
      String jsonString = "{"RollNo" : "1","Name" : "Mark"}"; 
      try { 
         Student student = mapper.readerFor(Student.class).readValue(jsonString); 
         System.out.println(student.getProperties().get("Name")); 
         System.out.println(student.getProperties().get("RollNo")); 
      }
      catch (IOException e) {
         e.printStackTrace(); 
      } 
   }
}
class Student {
   private Map<String, String> properties; 
   pubpc Student(){ 
      properties = new HashMap<>(); 
   }  
   pubpc Map<String, String> getProperties(){ 
      return properties; 
   } 
   @JsonAnySetter 
   pubpc void add(String property, String value){ 
      properties.put(property, value); 
   }   
}

Output

Mark 
1 

Jackson Annotations - @JsonSetter

@JsonSetter allows a specific method to be marked as setter method.

Example @JsonSetter

import java.io.IOException; 
import com.fasterxml.jackson.annotation.JsonSetter; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]){ 
      ObjectMapper mapper = new ObjectMapper(); 
      String jsonString = "{"rollNo":1,"name":"Marks"}"; 

      try { 
         Student student = mapper.readerFor(Student.class).readValue(jsonString);
         System.out.println(student.name); 
      }
      catch (IOException e) {
         e.printStackTrace(); 
      }   
   } 
}
class Student { 
   pubpc int rollNo; 
   pubpc String name; 
   @JsonSetter("name") 
   pubpc void setTheName(String name) { 
      this.name = name; 
   }  
}

Output

Marks 

Jackson Annotations - @JsonDeseriapze

@JsonDeseriapze is used to specify custom deseriapzer to unmarshall the json object.

Example @JsonDeseriapze

import java.io.IOException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

import com.fasterxml.jackson.core.JsonParser; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.DeseriapzationContext; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.annotation.JsonDeseriapze; 
import com.fasterxml.jackson.databind.deser.std.StdDeseriapzer; 

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws ParseException{ 
      ObjectMapper mapper = new ObjectMapper(); 
      String jsonString = "{"name":"Mark","dateOfBirth":"20-12-1984"}"; 
      try {     
         Student student = mapper
            .readerFor(Student.class) 
            .readValue(jsonString); 
         System.out.println(student.dateOfBirth); 
      } 
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }
}
class Student {
   pubpc String name; 
   @JsonDeseriapze(using = CustomDateDeseriapzer.class) 
   pubpc Date dateOfBirth; 
}
class CustomDateDeseriapzer extends StdDeseriapzer<Date> {
   private static final long serialVersionUID = 1L;
   private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
   pubpc CustomDateDeseriapzer() { 
      this(null); 
   } 
   pubpc CustomDateDeseriapzer(Class<Date> t) { 
      super(t); 
   } 
   @Override 
   pubpc Date deseriapze(JsonParser parser, DeseriapzationContext context) 
      throws IOException, JsonProcessingException { 
      
      String date = parser.getText(); 
      try { 
         return formatter.parse(date); 
      } 
      catch (ParseException e) { 
         e.printStackTrace(); 
      }    
      return null; 
   }   
}

Output

Thu Dec 20 00:00:00 IST 1984 

Jackson Annotations - @JsonEnumDefaultValue

@JsonEnumDefaultValue is used to deseriapze an unknown enum value using a default value.

Example @JsonEnumDefaultValue

import java.io.IOException; 
import java.text.ParseException; 

import com.fasterxml.jackson.annotation.JsonEnumDefaultValue; 
import com.fasterxml.jackson.databind.DeseriapzationFeature; 
import com.fasterxml.jackson.databind.ObjectMapper; 

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws ParseException{
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(DeseriapzationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
      String jsonString = ""abc""; 
      try {
         LETTERS value = mapper.readValue(jsonString, LETTERS.class); 
         System.out.println(value); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }   
   }  
}
enum LETTERS {
   A, B, @JsonEnumDefaultValue UNKNOWN 
} 

Output

UNKNOWN 

Jackson Annotations - @JsonIgnoreProperties

@JsonIgnoreProperties is used at class level to mark a property or pst of properties to be ignored.

Example - @JsonIgnoreProperties

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) {
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student(1,11,"1ab","Mark");       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) { 
         e.printStackTrace();
      }   
   }
}
@JsonIgnoreProperties({ "id", "systemId" })
class Student {
   pubpc int id;
   pubpc String systemId;
   pubpc int rollNo;
   pubpc String name;

   Student(int id, int rollNo, String systemId, String name){
      this.id = id;
      this.systemId = systemId;
      this.rollNo = rollNo;
      this.name = name;
   }
}

Output

{
   "rollNo" : 11,
   "name" : "Mark"
}

Jackson Annotations - @JsonIgnore

@JsonIgnore is used at field level to mark a property or pst of properties to be ignored.

Example - @JsonIgnore

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try{
         Student student = new Student(1,11,"1ab","Mark");       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) { 
         e.printStackTrace();
      }     
   }
}
class Student { 
   pubpc int id;
   @JsonIgnore
   pubpc String systemId;
   pubpc int rollNo;
   pubpc String name;

   Student(int id, int rollNo, String systemId, String name){
      this.id = id;
      this.systemId = systemId;
      this.rollNo = rollNo;
      this.name = name;
   }
}

Output

{
   "id" : 1,
   "rollNo" : 11,
   "name" : "Mark"
}

Jackson Annotations - @JsonIgnoreType

@JsonIgnoreType is used at mark a property of special type to be ignored.

Example - @JsonIgnoreType

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student(1,11,"1ab","Mark");       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) { 
         e.printStackTrace();
      }     
   }
}
class Student { 
   pubpc int id;
   @JsonIgnore
   pubpc String systemId;
   pubpc int rollNo;
   pubpc Name nameObj;

   Student(int id, int rollNo, String systemId, String name){
      this.id = id;
      this.systemId = systemId;
      this.rollNo = rollNo;
      nameObj = new Name(name);
   }

   @JsonIgnoreType
   class Name {
      pubpc String name;
      Name(String name){
         this.name = name;
      }       
   }
}

Output

{
   "id" : 1,
   "systemId" : "1ab",
   "rollNo" : 11
}

Jackson Annotations - @JsonInclude

@JsonInclude is used at exclude properties having null/empty or default values.

Example - @JsonInclude

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student(1,null);       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) { 
         e.printStackTrace();
      }     
   }
}
@JsonInclude(JsonInclude.Include.NON_NULL)
class Student { 
   pubpc int id; 
   pubpc String name;

   Student(int id,String name){
      this.id = id;
      this.name = name;
   }   
}

Output

{
   "id" : 1
}

Jackson Annotations - @JsonAutoDetect

@JsonAutoDetect can be used to include properties which are not accessible otherwise.

Example - @JsonAutoDetect

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try{
         Student student = new Student(1,"Mark");       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) {
         e.printStackTrace();
      }     
   }
}
@JsonAutoDetect(fieldVisibipty = JsonAutoDetect.Visibipty.ANY)
class Student { 
   private int id; 
   private String name;

   Student(int id,String name) {
      this.id = id;
      this.name = name;
   }   
}

Output

{
   "id" : 1,
   "name" : "Mark"
}

Jackson Annotations - @JsonTypeInfo

@JsonTypeInfo is used to indicate details of type information which is to be included in seriapzation and de-seriapzation.

Example - @JsonTypeInfo

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException {
      Shape shape = new JacksonTester.Circle("CustomCircle", 1);
      String result = new ObjectMapper()
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(shape);
      System.out.println(result);   
      String json = "{"name":"CustomCircle","radius":1.0, "type":"circle"}";
      Circle circle = new ObjectMapper().readerFor(Shape.class).readValue(json);
      System.out.println(circle.name);
   }
   @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, property = "type") @JsonSubTypes({
      
      @JsonSubTypes.Type(value = Square.class, name = "square"),
      @JsonSubTypes.Type(value = Circle.class, name = "circle")
   })
   static class Shape {
      pubpc String name;    
      Shape(String name){
         this.name = name;
      }
   }
   @JsonTypeName("square")
   static class Square extends Shape {
      pubpc double length;
      Square(){
         this(null,0.0);
      }
      Square(String name, double length){
         super(name);
         this.length = length;
      }
   }
   @JsonTypeName("circle")
   static class Circle extends Shape {
      pubpc double radius;  
      Circle(){
         this(null,0.0);
      }
      Circle(String name, double radius) {
         super(name);
         this.radius = radius;
      }
   }
}

Output

{
   "type" : "circle",
   "name" : "CustomCircle",
   "radius" : 1.0
}
CustomCircle

Jackson Annotations - @JsonSubTypes

@JsonSubTypes is used to indicate subtypes of types annotated.

Example - @JsonSubTypes

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException{
      Shape shape = new JacksonTester.Circle("CustomCircle", 1);
      String result = new ObjectMapper()
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(shape);
      System.out.println(result);   
      String json = "{"name":"CustomCircle","radius":1.0, "type":"circle"}";
      Circle circle = new ObjectMapper().readerFor(Shape.class).readValue(json);
      System.out.println(circle.name);
   }
   @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, property = "type") @JsonSubTypes({
         
      @JsonSubTypes.Type(value = Square.class, name = "square"),
      @JsonSubTypes.Type(value = Circle.class, name = "circle")
   })
   static class Shape {
      pubpc String name;    
      Shape(String name) {
         this.name = name;
      }
   }
   @JsonTypeName("square")
   static class Square extends Shape {
      pubpc double length;
      Square(){
         this(null,0.0);
      }
      Square(String name, double length){
         super(name);
         this.length = length;
      }
   }
   @JsonTypeName("circle")
   static class Circle extends Shape {
      pubpc double radius;  
      Circle(){
         this(null,0.0);
      }
      Circle(String name, double radius){
         super(name);
         this.radius = radius;
      }
   }   
}

Output

{
   "type" : "circle",
   "name" : "CustomCircle",
   "radius" : 1.0
}
CustomCircle

Jackson Annotations - @JsonTypeName

@JsonTypeName is used to set type names to be used for annotated class.

Example - @JsonTypeName

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException {
      Shape shape = new JacksonTester.Circle("CustomCircle", 1);
      String result = new ObjectMapper()
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(shape);
      System.out.println(result);   
      String json = "{"name":"CustomCircle","radius":1.0, "type":"circle"}";
      Circle circle = new ObjectMapper().readerFor(Shape.class).readValue(json);
      System.out.println(circle.name);
   }
   @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = As.PROPERTY, property = "type") @JsonSubTypes({
      
      @JsonSubTypes.Type(value = Square.class, name = "square"),
      @JsonSubTypes.Type(value = Circle.class, name = "circle")
   })
   static class Shape {
      pubpc String name;
      Shape(String name){
         this.name = name;
      }            
   }
   @JsonTypeName("square")
   static class Square extends Shape {
      pubpc double length;
      Square(){
         this(null,0.0);
      }
      Square(String name, double length){
         super(name);
         this.length = length;
      }
   }
   @JsonTypeName("circle")
   static class Circle extends Shape {
      pubpc double radius;  
      Circle(){
         this(null,0.0);
      }
      Circle(String name, double radius){
         super(name);
         this.radius = radius;
      }
   }    
}

Output

{
   "type" : "circle",
   "name" : "CustomCircle",
   "radius" : 1.0
}
CustomCircle

Jackson Annotations - @JsonProperty

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.

Example - @JsonProperty

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      String json = "{"id" : 1}";
      Student student = mapper.readerFor(Student.class).readValue(json);
      System.out.println(student.getTheId());
   }
}
class Student {
   private int id;
   Student(){}
   Student(int id){
      this.id = id;
   }
   @JsonProperty("id")
   pubpc int getTheId() {
      return id;
   }
   @JsonProperty("id")
   pubpc void setTheId(int id) {
      this.id = id;
   }   
}

Output

1

Jackson Annotations - @JsonFormat

@JsonFormat is used to specify format while seriapzation or de-seriapzation. It is mostly used with Date fields.

Example - @JsonFormat

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");

      Student student = new Student(1, date);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student { 
   pubpc int id;
   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
   pubpc Date birthDate;
   Student(int id, Date birthDate){
      this.id = id;
      this.birthDate = birthDate;
   } 
}

Output

{
   "id" : 1,
   "birthDate" : "19-12-1984"
}

Jackson Annotations - @JsonUnwrapped

@JsonUnwrapped is used to unwrap values of objects during seriapzation or de-seriapzation.

Example - @JsonUnwrapped

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");
      Student.Name name = new Student.Name();
      name.first = "Jane";
      name.last = "Doe";
      Student student = new Student(1, name);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student {
   pubpc int id;   
   @JsonUnwrapped
   pubpc Name name;
   Student(int id, Name name){
      this.id = id;
      this.name = name;
   }
   static class Name {
      pubpc String first;
      pubpc String last;
   }
}

Output

{
   "id" : 1,
   "first" : "Jane",
   "last" : "Doe"
}

Jackson Annotations - @JsonView

@JsonView is used to control values to be seriapzed or not.

Example - @JsonView

import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1, "Mark", 12);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .withView(Views.Pubpc.class)
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student {
   @JsonView(Views.Pubpc.class)
   pubpc int id;
   @JsonView(Views.Pubpc.class)
   pubpc String name;
   @JsonView(Views.Internal.class)
   pubpc int age;

   Student(int id, String name, int age) {
      this.id = id;
      this.name = name;
      this.age = age;
   }
}
class Views {
   static class Pubpc {}
   static class Internal extends Pubpc {}
}

Output

{
   "id" : 1,
   "name" : "Mark"
}

Jackson Annotations - @JsonManagedReference

@JsonManagedReferences and JsonBackReferences are used to display objects with parent child relationship. @JsonManagedReferences is used to refer to parent object and @JsonBackReferences is used to mark child objects.

Example - @JsonManagedReferences

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1, "Mark");
      Book book1 = new Book(1,"Learn HTML", student);
      Book book2 = new Book(1,"Learn JAVA", student);

      student.addBook(book1);
      student.addBook(book2);

      String jsonString = mapper 
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(book1);
      System.out.println(jsonString);
   }
}
class Student {
   pubpc int rollNo;
   pubpc String name;

   @JsonBackReference
   pubpc List<Book> books;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
      this.books = new ArrayList<Book>();
   }
   pubpc void addBook(Book book){
      books.add(book);
   }
}
class Book {
   pubpc int id;
   pubpc String name;

   Book(int id, String name, Student owner){
      this.id = id;
      this.name = name;
      this.owner = owner;
   }
   @JsonManagedReference
   pubpc Student owner;
}

Output

{
   "id" : 1,
   "name" : "Learn HTML",
   "owner" : {
      "rollNo" : 1,
      "name" : "Mark"
   }
}

Jackson Annotations - @JsonBackReference

@JsonManagedReferences and JsonBackReferences are used to display objects with parent child relationship. @JsonManagedReferences is used to refer to parent object and @JsonBackReferences is used to mark child objects.

Example - @JsonBackReferences

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1, "Mark");
      Book book1 = new Book(1,"Learn HTML", student);
      Book book2 = new Book(1,"Learn JAVA", student);

      student.addBook(book1);
      student.addBook(book2);

      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(book1);
      System.out.println(jsonString);
   }
}
class Student { 
   pubpc int rollNo;
   pubpc String name;

   @JsonBackReference
   pubpc List<Book> books;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
      this.books = new ArrayList<Book>();
   }
   pubpc void addBook(Book book){
      books.add(book);
   }
}
class Book {
   pubpc int id;
   pubpc String name;

   Book(int id, String name, Student owner) {
      this.id = id;
      this.name = name;
      this.owner = owner;
   }

   @JsonManagedReference
   pubpc Student owner;
}

Output

{
   "id" : 1,
   "name" : "Learn HTML",
   "owner" : {
      "rollNo" : 1,
      "name" : "Mark"
   }
}

Jackson Annotations - @JsonIdentityInfo

@JsonIdentityInfo is used when objects have parent child relationship. @JsonIdentityInfo is used to indicate that object identity will be used during seriapzation/de-seriapzation.

Example - @JsonIdentityInfo

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1,13, "Mark");
      Book book1 = new Book(1,"Learn HTML", student);
      Book book2 = new Book(2,"Learn JAVA", student);

      student.addBook(book1);
      student.addBook(book2);

      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(book1);
      System.out.println(jsonString);
   }
}
@JsonIdentityInfo(
   generator = ObjectIdGenerators.PropertyGenerator.class,
   property = "id")
class Student { 
   pubpc int id;
   pubpc int rollNo;
   pubpc String name;
   pubpc List<Book> books;
   
   Student(int id, int rollNo, String name){
      this.id = id;
      this.rollNo = rollNo;
      this.name = name;
      this.books = new ArrayList<Book>();
   }
   pubpc void addBook(Book book){
      books.add(book);
   }
}
@JsonIdentityInfo(
   generator = ObjectIdGenerators.PropertyGenerator.class,
   property = "id")
class Book{
   pubpc int id;
   pubpc String name;

   Book(int id, String name, Student owner){
      this.id = id;
      this.name = name;
      this.owner = owner;
   }
   pubpc Student owner;
}

Output

{
   "id" : 1,
   "name" : "Learn HTML",
   "owner" : {
      "id" : 1,
      "rollNo" : 13,
      "name" : "Mark",
      "books" : [ 
         1, {
            "id" : 2,
            "name" : "Learn JAVA",
            "owner" : 1
         }  
      ]
   }
}

Jackson Annotations - @JsonFilter

@JsonFilter is used to apply filter during seriapzation/de-seriapzation pke which properties are to be used or not.

Example - @JsonFilter

import java.io.IOException;
import java.text.ParseException;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1,13, "Mark");
      
      FilterProvider filters = new SimpleFilterProvider() .addFilter(
         "nameFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));
      
      String jsonString = mapper.writer(filters)             
         .withDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
@JsonFilter("nameFilter")
class Student {
   pubpc int id;
   pubpc int rollNo;
   pubpc String name;

   Student(int id, int rollNo, String name) {
      this.id = id;
      this.rollNo = rollNo;
      this.name = name;
   }   
}

Output

{
   "name" : "Mark"
}

Jackson Annotations - Custom Annotation

We can create custom annotation easily using @JacksonAnnotationsInside annotation.

Example - Custom Annotation

import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPopcy;
import java.text.ParseException;

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1,13, "Mark");

      String jsonString = mapper  
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
@CustomAnnotation
class Student {
   pubpc int id;
   pubpc int rollNo;
   pubpc String name;
   pubpc String otherDetails;

   Student(int id, int rollNo, String name){
      this.id = id;
      this.rollNo = rollNo;
      this.name = name;
   }   
}
@Retention(RetentionPopcy.RUNTIME)
@JacksonAnnotationsInside
@JsonInclude(value = Include.NON_NULL)
@JsonPropertyOrder({ "rollNo", "id", "name" })
@interface CustomAnnotation {}

Output

{
   "rollNo" : 13,
   "id" : 1,
   "name" : "Mark"
}

Jackson Annotations - Mixin

Mixin Annotation is a way to associate annotations without modifying the target class. See the example below −

Example - Mixin Annotation

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]) {
      ObjectMapper mapper = new ObjectMapper();
      try {
         Student student = new Student(1,11,"1ab","Mark");       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);

         ObjectMapper mapper1 = new ObjectMapper();
         mapper1.addMixIn(Name.class, MixInForIgnoreType.class);
         jsonString = mapper1
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) { 
         e.printStackTrace();
      }     
   }
}
class Student {
   pubpc int id;
   pubpc String systemId;
   pubpc int rollNo;
   pubpc Name nameObj;

   Student(int id, int rollNo, String systemId, String name) {
      this.id = id;
      this.systemId = systemId;
      this.rollNo = rollNo;
      nameObj = new Name(name);
   }
}
class Name {
   pubpc String name;
   Name(String name){
      this.name = name;
   }       
}
@JsonIgnoreType
class MixInForIgnoreType {}

Output

{
   "id" : 1,
   "systemId" : "1ab",
   "rollNo" : 11,
   "nameObj" : {
      "name" : "Mark"
   }
}
{
   "id" : 1,
   "systemId" : "1ab",
   "rollNo" : 11
}

Jackson Annotations - Disable

We can disable jackson annotations using disable() function of ObjectMapper.

Example - Disabpng Annotation

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

pubpc class JacksonTester {
   pubpc static void main(String args[]){
      ObjectMapper mapper = new ObjectMapper();
      try{
         Student student = new Student(1,11,"1ab","Mark");       
         String jsonString = mapper
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);

         ObjectMapper mapper1 = new ObjectMapper();
         mapper1.disable(MapperFeature.USE_ANNOTATIONS);
         jsonString = mapper1
            .writerWithDefaultPrettyPrinter()
            .writeValueAsString(student);
         System.out.println(jsonString);
      }
      catch (IOException e) { 
         e.printStackTrace();
      }     
   }
}
class Student {
   pubpc int id;
   pubpc String systemId;
   pubpc int rollNo;
   pubpc Name nameObj;

   Student(int id, int rollNo, String systemId, String name){
      this.id = id;
      this.systemId = systemId;
      this.rollNo = rollNo;
      nameObj = new Name(name);
   }
}
@JsonIgnoreType
class Name {
   pubpc String name;
   Name(String name){
      this.name = name;
   }       
}

Output

{
   "id" : 1,
   "systemId" : "1ab",
   "rollNo" : 11
}
{
   "id" : 1,
   "systemId" : "1ab",
   "rollNo" : 11,
   "nameObj" : {
      "name" : "Mark"
   }
}
Advertisements