Skip to content

YearKeyDeserializer doesn't work with non-padded year values #51

Closed
@sladkoff

Description

@sladkoff

Description & proposal

The YearKeyDeserializer is unable to deserialize keys that are not in the format yyyy (e.g. "1"). It expects the year to be padded with zeros ("0001").

In contrast, the YearDeserializer is in fact working correctly and can handle non-padded values as well.

This could probably be fixed by changing the YearKeyDeserializer#deserialize:30 to something like this (we've currently registered a custom deserializer that does this):

@Override
protected Year deserialize(String key, DeserializationContext ctxt) throws IOException {
-    try {
-        return Year.parse(key, FORMATTER);
+        return Year.of(Integer.parseInt(key));
-    } catch (DateTimeException e) {
-        return _rethrowDateTimeException(ctxt, Year.class, e, key);
-    }
}

Steps to reproduce

Here's a simple test to demonstrate the behavior:

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());

@Test
public void serializeAndDeserializeYearKey() throws IOException {
    Map<Year, Float> testMap = Collections.singletonMap(Year.of(1), 1F);

    String serialized = OBJECT_MAPPER.writeValueAsString(testMap);

    TypeReference<Map<Year, Float>> yearFloatTypeReference = new TypeReference<Map<Year, Float>>() {};

    Map<Year, Float> deserialized = OBJECT_MAPPER.readValue(serialized, yearFloatTypeReference);

    assertThat(deserialized).isEqualTo(testMap);
}

The above will throw java.time.format.DateTimeParseException: Text '1' could not be parsed at index 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions