繁体   English   中英

使用 ObjectMapper 将 JSON 日期格式从 ZonedDateTime 序列化为自定义日期格式

[英]Serialize JSON date format from ZonedDateTime to custom date format using ObjectMapper

ObjectMapper 不会将ZonedDateTime object 格式化为自定义的。

POJO 不在我的控制之下,所以我无法更改它。 我需要为 WS 序列化 POJO object。 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:

@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;
}

而这个 class:

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;
}

在我的代码中,我自动装配了 object 映射器并像这样序列化这个 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"

创建具有返回类型字符串的 getter 并将其标记为属性(并将您的原始 getter 或属性标记为@JsonIgnored )。 就像这样:

@JsonGetter("startDate")
public String getStartDateAsString() {
    return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(startDate);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM