I think I must be misunderstanding how Zones work in java's ZonedDateTime class. When I use Jackson to serialize and then deserialize now(), the deserialized value has getZone() == "UTC" instead of the "Z" in the serialized value. Can anyone explain to me why this is and what I should be doing instead?
我想我必须误解Zones在java的ZonedDateTime类中的工作方式。当我使用Jackson序列化然后反序列化now()时,反序列化的值在序列化值中具有getZone()==“UTC”而不是“Z”。谁能向我解释为什么这是我应该做的事情呢?
The code below prints:
以下代码打印:
{"t":"2017-11-24T18:00:08.425Z"}
Data [t=2017-11-24T18:00:08.425Z]
Data [t=2017-11-24T18:00:08.425Z[UTC]]
Z
UTC
The java source:
java源码:
<!-- language: java -->
package model;
import static org.junit.Assert.*;
import java.io.IOException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class ZonedDateTimeSerializationTest {
static public class Data {
@Override
public String toString() {
return "Data [t=" + t + "]";
}
public ZonedDateTime getT() {
return t;
}
public void setT(ZonedDateTime t) {
this.t = t;
}
ZonedDateTime t = ZonedDateTime.now(ZoneOffset.UTC);
};
@Test
public void testDeSer() throws IOException {
Data d = new Data();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
String serialized = objectMapper.writer()
.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.writeValueAsString(d);
System.out.println(serialized);
Data d2 = objectMapper.readValue(serialized, Data.class);
System.out.println(d);
System.out.println(d2);
System.out.println(d.getT().getZone());
System.out.println(d2.getT().getZone());
// this fails
assertEquals(d, d2);
}
}
1 个解决方案
#1
4
By default, during deserialization of a ZonedDateTime
, Jackson will adjust the parsed timezone to the contextually provided one. You can modify this behavior with this setting so that the parsed ZonedDateTime
will stay at Z
:
默认情况下,在ZonedDateTime反序列化期间,Jackson会将解析后的时区调整为上下文提供的时区。您可以使用此设置修改此行为,以便解析的ZonedDateTime将保留在Z:
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
More details here
更多细节在这里
#1
4
By default, during deserialization of a ZonedDateTime
, Jackson will adjust the parsed timezone to the contextually provided one. You can modify this behavior with this setting so that the parsed ZonedDateTime
will stay at Z
:
默认情况下,在ZonedDateTime反序列化期间,Jackson会将解析后的时区调整为上下文提供的时区。您可以使用此设置修改此行为,以便解析的ZonedDateTime将保留在Z:
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
More details here
更多细节在这里