如何在使用 Jackson 反序列化 OffsetDateTime 时保留偏移量
How to preserve the offset while deserializing OffsetDateTime with Jackson
在传入的 JSON 中,我有一个符合 ISO8601 标准的日期时间字段,其中包含时区偏移量。我想保留此偏移量,但不幸的是,杰克逊在反序列化此字段时默认为 GMT/UTC(我从 http://wiki.fasterxml.com/JacksonFAQDateHandling 中了解到)。
@RunWith(JUnit4.class)
public class JacksonOffsetDateTimeTest {
private ObjectMapper objectMapper;
@Before
public void init() {
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(new JavaTimeModule())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
@Test
public void test() throws IOException {
final String json = "{ \"date\": \"2000-01-01T12:00:00.000-04:00\" }";
final JsonType instance = objectMapper.readValue(json, JsonType.class);
assertEquals(ZoneOffset.ofHours(-4), instance.getDate().getOffset());
}
}
public class JsonType {
private OffsetDateTime date;
// getter, setter
}
我得到的是:
java.lang.AssertionError: expected:<-04:00> but was:<Z>
如何使返回的 OffsetDateTime 包含原始 Offset?
我正在使用 Jackson 2.8.3。
你可以试试吗
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
?
根据您链接的常见问题解答,它应该为您提供格式 1970-01-01T00:00:00.000+0000
。此格式包含时区偏移量 (+0000
)。
将您的对象映射器更改为此以禁用 ADJUST_DATES_TO_CONTEXT_TIME_ZONE。
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(new JavaTimeModule())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
.build();
在传入的 JSON 中,我有一个符合 ISO8601 标准的日期时间字段,其中包含时区偏移量。我想保留此偏移量,但不幸的是,杰克逊在反序列化此字段时默认为 GMT/UTC(我从 http://wiki.fasterxml.com/JacksonFAQDateHandling 中了解到)。
@RunWith(JUnit4.class)
public class JacksonOffsetDateTimeTest {
private ObjectMapper objectMapper;
@Before
public void init() {
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(new JavaTimeModule())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
@Test
public void test() throws IOException {
final String json = "{ \"date\": \"2000-01-01T12:00:00.000-04:00\" }";
final JsonType instance = objectMapper.readValue(json, JsonType.class);
assertEquals(ZoneOffset.ofHours(-4), instance.getDate().getOffset());
}
}
public class JsonType {
private OffsetDateTime date;
// getter, setter
}
我得到的是:
java.lang.AssertionError: expected:<-04:00> but was:<Z>
如何使返回的 OffsetDateTime 包含原始 Offset?
我正在使用 Jackson 2.8.3。
你可以试试吗
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
?
根据您链接的常见问题解答,它应该为您提供格式 1970-01-01T00:00:00.000+0000
。此格式包含时区偏移量 (+0000
)。
将您的对象映射器更改为此以禁用 ADJUST_DATES_TO_CONTEXT_TIME_ZONE。
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(new JavaTimeModule())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
.build();