FasterXML / jackson-modules-java8

Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)
Apache License 2.0
401 stars 117 forks source link

ZonedDateTime in map keys ignores option to write Zone IDs #127

Closed zmumi closed 5 years ago

zmumi commented 5 years ago

As of v2.9.9, the following fails:

class Sample {
    private Map<ZonedDateTime, ZonedDateTime> map;
    private ZonedDateTime dateTime;

    public Sample() {
    }

    public ZonedDateTime getDateTime() {
        return dateTime;
    }

    public void setDateTime(ZonedDateTime dateTime) {
        this.dateTime = dateTime;
    }

    public Map<ZonedDateTime, ZonedDateTime> getMap() {
        return map;
    }

    public void setMap(Map<ZonedDateTime, ZonedDateTime> map) {
        this.map = map;
    }
}

public class JacksonTest {

    @Test
    public void shouldSerializeZoneIdInMapKeys() throws IOException {
        // given
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new Jdk8Module());
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);

        final ZonedDateTime datetime = ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Warsaw]");
        final HashMap<ZonedDateTime, ZonedDateTime> map = new HashMap<>();
        map.put(datetime, datetime);
        final Sample sample = new Sample();
        sample.setMap(map);
        sample.setDateTime(datetime);

        // when
        final String value = objectMapper.writeValueAsString(sample);

        // then
        assertThat(value).isEqualTo("{\"map\":" +
                "{\"2007-12-03T10:15:30+01:00[Europe/Warsaw]\":\"2007-12-03T10:15:30+01:00[Europe/Warsaw]\"}," +
                "\"dateTime\":\"2007-12-03T10:15:30+01:00[Europe/Warsaw]\"" +
                "}");
    }
}

I'd expect that Zone ID is written not only in map keys but also in map values. Currently SerializationFeature.WRITE_DATES_WITH_ZONE_ID has no impact on map keys.

Sample project: test.zip

cowtowncoder commented 5 years ago

Key serializers/deserializers are different from value (de)serializers which probably explains discrepancy.

But just to make sure: which part (or both) is failing; key or value serializer?

cowtowncoder commented 5 years ago

Tagging with easy just to denote issues where new contributors could probably help most.

zmumi commented 5 years ago

But just to make sure: which part (or both) is failing; key or value serializer?

Key serializer.

cowtowncoder commented 5 years ago

@zmumi Thank you, makes sense, but just wanted to double-check.