English 中文(简体)
Jackson - @JsonDeserialize
  • 时间:2024-11-05

Jackson Annotations - @JsonDeseriapze


Previous Page Next Page  

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