如何在 Java 中使用 Jackson 對映多種日期格式?


Jackson是一個基於 Java 的庫,它可以用來將 Java 物件轉換為 JSON,以及將 JSON 轉換為 Java 物件。我們可以使用@JsonFormat 註解在 Jackson 庫中對映多種日期格式,它是一個通用註解,用於配置屬性值的序列化細節。@JsonFormat有三個重要的欄位:shape、patterntimezoneshape欄位可以定義用於序列化的結構(JsonFormat.Shape.NUMBERJsonFormat.Shape.STRING),pattern欄位可用於序列化和反序列化。對於日期,模式包含SimpleDateFormat相容的定義,最後,timezone欄位可用於序列化,預設值為系統預設時區。

語法

@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);
   }
}
// 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")
   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
]

更新於: 06-Jul-2020

3K+ 閱讀量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告