📜  Jackson注释-@JsonDeserialize

📅  最后修改于: 2020-11-16 07:37:51             🧑  作者: Mango


@JsonDeserialize用于指定自定义反序列化器以解组json对象。

例子@JsonDeserialize

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.DeserializationContext; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 
import com.fasterxml.jackson.databind.deser.std.StdDeserializer; 

public class JacksonTester {
   public 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 {
   public String name; 
   @JsonDeserialize(using = CustomDateDeserializer.class) 
   public Date dateOfBirth; 
}
class CustomDateDeserializer extends StdDeserializer {
   private static final long serialVersionUID = 1L;
   private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
   public CustomDateDeserializer() { 
      this(null); 
   } 
   public CustomDateDeserializer(Class t) { 
      super(t); 
   } 
   @Override 
   public Date deserialize(JsonParser parser, DeserializationContext context) 
      throws IOException, JsonProcessingException { 
      
      String date = parser.getText(); 
      try { 
         return formatter.parse(date); 
      } 
      catch (ParseException e) { 
         e.printStackTrace(); 
      }    
      return null; 
   }   
}

输出

Thu Dec 20 00:00:00 IST 1984