Jackson Annotations - @JsonCreator



@JsonCreator is used to fine tune the constructor or factory method used in deserialization. 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; 

public class JacksonTester {
   public 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 {
   public String name; 
   public int rollNo; 

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

Output

1, Mark 
Advertisements