Jackson是一個基於 Java 的函式庫,它對於將 Java 物件轉換為 JSON 以及將 JSON 轉換為 Java 物件非常有用。我們可以使用@JsonFormat註釋來映射Jackson庫中的多種日期格式,它是一個通用註釋,用於配置屬性值如何序列化的詳細資訊。 @JsonFormat 有三個重要欄位:形狀、模式和時區。 shape 字段可以定義用於序列化的結構(JsonFormat.Shape.NUMBER和JsonFormat.Shape.STRING),模式字段可用於序列化和反序列化。對於日期,此模式包含SimpleDateFormat 相容定義,最後,timezone 欄位可用於序列化,預設為系統預設時區。
@Target(value={ANNOTATION_TYPE,FIELD,METHOD,PARAMETER,TYPE}) @Retention(value=RUNTIME) public @interface JsonFormat<strong> </strong>
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.<strong>readValue</strong>(reader, <strong>Employee.class</strong>); System.out.println(employee); } } // Employee class 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")<strong> </strong> 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; } <strong> </strong> @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 ]
以上是在Java中,我們如何使用Jackson映射多個日期格式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!