【发布时间】:2020-01-28 05:38:23
【问题描述】:
使用 jshell 版本 11.0.1,我正在尝试测试 java.time.OffsetDateTime 的 Jackson 序列化。我希望它以 ISO-8601 格式序列化,但它没有按预期工作。 为什么它仍然被序列化为对象而不是 ISO 8601?
这是我启动 jshell 的方式
jshell --class-path ~/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.8.9/jackson-databind-2.8.9.jar:~/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.8.9/jackson-core-2.8.9.jar:~/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.8.9/jackson-annotations-2.8.9.jar:~/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.8.11/jackson-datatype-jsr310-2.8.11.jar
这是我在 jshell 中运行的代码
import com.fasterxml.jackson.databind.*;
import java.time.*;
import com.fasterxml.jackson.datatype.jsr310.*;
ObjectMapper mapper = new ObjectMapper();
mapper = mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.canSerialize(OffsetDateTime.class);
mapper.writeValueAsString(OffsetDateTime.now());
这是输出
| Welcome to JShell -- Version 11.0.1
| For an introduction type: /help intro
jshell> import com.fasterxml.jackson.databind.*;
jshell> import java.time.*;
jshell> import com.fasterxml.jackson.datatype.jsr310.*;
jshell> ObjectMapper mapper = new ObjectMapper();
mapper ==> com.fasterxml.jackson.databind.ObjectMapper@7fc229ab
jshell> mapper = mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper ==> com.fasterxml.jackson.databind.ObjectMapper@7fc229ab
jshell> mapper.canSerialize(OffsetDateTime.class);
$6 ==> true
jshell> mapper.writeValueAsString(OffsetDateTime.now());
$7 ==> "{\"offset\":{\"totalSeconds\":-25200,\"id\":\"-07:00\",\"rules\":{\"fixedOffset\":true,\"transitions\":[],\"transitionRules\":[]}},\"month\":\"SEPTEMBER\",\"dayOfWeek\":\"FRIDAY\",\"dayOfYear\":270,\"nano\":911405000,\"year\":2019,\"monthValue\":9,\"dayOfMonth\":27,\"hour\":16,\"minute\":33,\"second\":6}"
为什么它仍然被序列化为对象而不是 ISO 8601?
【问题讨论】: