Jackson 注解 - @JsonDeserialize
@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<Date> { private static final long serialVersionUID = 1L; private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); public CustomDateDeserializer() { this(null); } public CustomDateDeserializer(Class<Date> 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