java-为什么Jackson的默认解串器将Zone设置为UTC而不是Z?

我想我一定误会了Zones在Java的ZonedDateTime类中的工作方式.当我使用Jackson进行序列化然后对now()进行反序列化时,反序列化的值具有getZone()==“ UTC”而不是序列化值中的“ Z”.谁能向我解释为什么会这样,我应该怎么做?

下面的代码打印:

{"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

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);
    }
}

解决方法:

默认情况下,在对ZonedDateTime进行反序列化期间,Jackson会将解析的时区调整为上下文提供的时区.您可以使用此设置修改此行为,以使解析的ZonedDateTime保持在Z:

objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

更多细节here

上一篇:ZonedDateTime获取一段时间间隔的时间列表


下一篇:java – 尝试将PDT中的日期时间解析为ZonedDateTime表示