如何使用 Java 中的 Jackson 映射多种日期格式?
javajsonobject oriented programmingprogramming更新于 2025/7/17 7:08:17
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 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

