ObjectMapper 不会将 ZonedDateTime
对象格式化为自定义对象。
POJO 不在我的控制之下,所以我无法更改它。
我需要为 WS 序列化 POJO 对象。
POJO 有 ZonedDateTime
(我不知道为什么,因为它的日期来自数据库)。
我正在使用 Spring-boot 2.1.8.RELEASE,所以... 我将其放入我的依赖项中:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
我还在 application.properties 中添加了这个:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
在配置文件中,我在配置文件中添加了这个 bean,因为尽快配置 ObjectMapper 以接受更改很重要:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setTimeZone(TimeZone.getTimeZone(Locale.FRANCE.getDisplayName()));
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer());
mapper.registerModule(javaTimeModule);
return mapper;
}
这个类:
public class ZonedDateTimeSerializer extends JsonSerializer {
public static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ", Locale.FRANCE);
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(((ZonedDateTime)value).format(FORMATTER));
}
我有带有 ZonedDateTime
字段的 POJO:
public ZonedDateTime getStartDate() {
return this.startDate != null ? this.startDate.withNano(0).withZoneSameLocal(ZoneId.of("Europe/Paris")) : null;
}
public void setStartDate(ZonedDateTime startDate) {
this.startDate = startDate != null ? startDate.withNano(0).withZoneSameLocal(ZoneId.of("Europe/Paris")) : null;
}
在我的代码中,我 Autowiring 了对象映射器并像这样序列化这个 POJO:
private final ObjectMapper mapper;
public MyClass(ObjectMapper mapper) {
this.mapper = mapper;
}
...
mapper.writeValueAsString(contactVersion);
但是我得到的是这样的:
"startDate":{"offset":{"totalSeconds":7200,"id":"+02:00","rules":{"transitions":[],...
还有很多信息,当时的 82.634765625kb 信息,我想要的是:
"2019-10-15T17:00:53Z"
已解决:一切正常。 我使用 IntelliJ,我在 Weblogic 12.2.1.3.0 下部署为自动部署,可能是我没有运行 Maven 干净所以我只是运行 Maven 安装并在 Debug模式下运行它所以它在没有 WRITE_DATE_AS_TIMESTAMPS=false 属性的情况下启动旧的 application.properties 文件。 我真的不知道,但它有效,应该是这样的。
最佳答案
创建一个带有返回类型字符串的 getter 并将其标记为属性(并将您的原始 getter 或属性标记为 @JsonIgnored
)。就这样:
@JsonGetter("startDate")
public String getStartDateAsString() {
return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(startDate);
}
关于java - 使用 ObjectMapper 将 JSON 日期格式从 ZonedDateTime 序列化为自定义日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401287/