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

时间:2017-11-24 18:07:49

标签: java json jackson zoneddatetime

我认为我必须误解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);
    }
}

1 个答案:

答案 0 :(得分:1)

我这样做实际上是为了保留时区:

mapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID)
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)