一个杰克逊 是一个基于Java的库,它可以为Java对象到JSON和JSON转换为Java对象很有用。我们可以使用@JsonFormat批注在Jackson库中映射多种日期格式,这是一种通用批注,用于配置如何序列化属性值的详细信息。该@JsonFormat 有三个重要领域:形状,图案, 和时区。的形状 字段可以定义结构,以使用用于序列化(JsonFormat.Shape.NUMBER和JsonFormat.Shape.STRING)时,图案 字段可序列化和反序列化使用。对于日期,该模式包含与SimpleDateFormat 兼容的定义,最后,时区 字段可用于序列化,默认为系统默认时区。
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE}) @Retention(value=RUNTIME) public @interface JsonFormat
import java.io.*; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonDateformatTest { final static ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws Exception { JacksonDateformatTest jacksonDateformat = new JacksonDateformatTest(); jacksonDateformat.dateformat(); } public void dateformat() throws Exception { String json = "{\"createDate\":\"1980-12-08\"," + "\"createDateGmt\":\"1980-12-08 3:00 PM GMT+1:00\"}"; Reader reader = new StringReader(json); Employee employee = mapper.readValue(reader, Employee.class); System.out.println(employee); } } //员工阶层 class Employee implements Serializable { @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "IST") private Date createDate; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z", timezone = "IST") private Date createDateGmt; public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getCreateDateGmt() { return createDateGmt; } public void setCreateDateGmt(Date createDateGmt) { this.createDateGmt = createDateGmt; } @Override public String toString() { return "Employee [\ncreateDate=" + createDate + ", \ncreateDateGmt=" + createDateGmt + "\n]"; } }
输出结果
Employee [ createDate=Mon Dec 08 00:00:00 IST 1980, createDateGmt=Mon Dec 08 07:30:00 IST 1980 ]