如何在 Java 中使用 Jackson 映射多种日期格式?
Jackson是一个基于 Java 的库,它可以用来将 Java 对象转换为 JSON,以及将 JSON 转换为 Java 对象。我们可以使用@JsonFormat 注解在 Jackson 库中映射多种日期格式,它是一个通用注解,用于配置属性值的序列化细节。@JsonFormat有三个重要的字段:shape、pattern和timezone。shape字段可以定义用于序列化的结构(JsonFormat.Shape.NUMBER 和 JsonFormat.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 ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP