English 中文(简体)
Jackson - @JsonCreator
  • 时间:2024-09-17

Jackson Annotations - @JsonCreator


Previous Page Next Page  

@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 
Advertisements