使用ObjectMapper

时间:2019-10-15 19:15:21

标签: java json spring-boot json-deserialization objectmapper

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

在我的代码中,我自动连接了对象映射器,并像这样使这个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安装并在调试模式下运行它,因此它在没有WRITE_DATE_AS_TIMESTAMPS = false属性的情况下启动了旧的application.properties文件。 我真的不知道,但是它可以工作,应该是这样。

1 个答案:

答案 0 :(得分:0)

创建一个带有返回类型字符串的吸气剂,并将其标记为属性(并将原始吸气剂或属性标记为@JsonIgnored)。就是这样:

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