问题描述
在我使用Spring Boot 2.0.0.M6
,Spring Framework 5.0.1.RELEASE
和Jackson 2.9.2
的项目中,我有一些与使用Jackson进行JSON序列化有关的问题.
I have some questions related to JSON serialization using Jackson in a project where I use Spring Boot 2.0.0.M6
, Spring Framework 5.0.1.RELEASE
and Jackson 2.9.2
.
我已经在application.properties
中配置了以下与Jackson相关的设置:
I have configured the following Jackson-related settings in application.properties
:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
串行化主要根据我的需要工作.不过,我注意到,如果000
,杰克逊似乎会缩短毫秒.
Serialization works mostly as I need. Nevertheless, I have noticed that Jackson seems to cut-off milliseconds if they are 000
.
测试1:以毫秒为单位的Instant Instant序列化设置为000
:
Test 1: Serialize Instant with milliseconds set to 000
:
- 使用
Instant.parse("2017-09-14T04:28:48.000Z")
初始化Instant字段 - 使用Jackson对其进行序列化
- 输出将为
"2017-09-14T04:28:48Z"
- Initialize Instant field using
Instant.parse("2017-09-14T04:28:48.000Z")
- Serialize it using Jackson
- Output will be
"2017-09-14T04:28:48Z"
测试2:将Instant(即时)序列化,并将毫秒设置为某些非000
值:
Test 2: Serialize Instant with milliseconds set to some non-000
value:
- 使用
Instant.parse("2017-09-14T04:28:48.100Z")
初始化Instant字段 - 使用Jackson对其进行序列化
- 输出将为
"2017-09-14T04:28:48.100Z"
- Initialize Instant field using
Instant.parse("2017-09-14T04:28:48.100Z")
- Serialize it using Jackson
- Output will be
"2017-09-14T04:28:48.100Z"
问题:
- 那是设计使然吗?
- 我可以采取什么措施来强制
000
的序列化吗?
- Is that behavior by design?
- Is there anything I can do to force serialization of
000
?
推荐答案
此此处 *.该链接包含两个解决方法
There appears to be a Jackson issue open for this here*. That link contains two workarounds
解决方法1
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
SimpleModule module = new SimpleModule();
module.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
@Override
public void serialize(ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ").format(zonedDateTime));
}
});
objectMapper.registerModule(module);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
解决方法2
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(ZonedDateTime.class,
new ZonedDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")));
ObjectMapper mapper = new ObjectMapper().registerModule(javaTimeModule);
这篇关于使用Jackson将即时序列化为ISO8601时的强制毫秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!