我使用Spring 4.3.4,Jackson 2.8.6和Tomcat 8.5.11。我有一些REST API:
@RestController
@RequestMapping(value = "/netadvice")
public class NetworkAdviceController {
...
@RequestMapping(
value = "/offsetDateTime",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public OffsetDateTime todayOffsetDateTime() {
return OffsetDateTime.now();
}
}
致电/netadvice/offsetDateTime
后,我希望以下列格式收到日期时间:2017-02-14T08:46:06.102Z
但我收到的内容如下:1487062454.957000000
。
我错了什么以及如何解决此问题?
以下代码是我的自定义日期时间序列化程序和反序列化程序:
@Configuration
public class JsonConfig {
public static final DateTimeFormatter FORMATTER = ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer());
javaTimeModule.addDeserializer(OffsetDateTime.class, new OffsetdateTimeDeserializer());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
public class OffsetDateTimeSerializer extends JsonSerializer<OffsetDateTime> {
@Override
public void serialize(OffsetDateTime value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeString(value.format(FORMATTER));
}
}
public class OffsetdateTimeDeserializer extends JsonDeserializer<OffsetDateTime> {
@Override
public OffsetDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return OffsetDateTime.parse(p.getValueAsString(), FORMATTER);
}
}
}