我们有一个使用 LocalDate 定义的 DTO:
@JsonProperty("dob")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate dob;
我们有一个 ObjectMapper 定义如下的代码:
private static final ObjectMapper makeMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new ParameterNamesModule());
mapper.registerModule(new Jdk8Module());
mapper.registerModule(new JavaTimeModule());
return mapper;
}
我们的 pom.xml 文件中包含所有 jackson-datababindm 核心 jsr310:
<!-- Jackson JSON Mapping -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.8</version>
</dependency>
因此,当我将对象转换为 JSON 字符串时:
String json = makeMapper().writeValueAsString(myobject);
dob 将 JSON 字符串写入为:
"dob":{ "year": 1964, "month": "FEBRUARY", "chronology": { "calendarType": "iso8601", "id": "ISO" }, "monthValue": 2, "dayOfMonth" :13,“dayOfWeek”:“THURSDAY”,“era”:“CE”,“dayOfYear”:44,“leapYear”:true}
而不是: "dob":"1964-02-13" 这是正确的。
所以,我不确定我是如何做到这一点的?
我想确保写出的日期是正确的,所以我可以重新解析回 LocalDate。或者,有没有办法可以获取现有的 JSON(扩展)并将其解析回 LocalDate?
谢谢!