yasson icon indicating copy to clipboard operation
yasson copied to clipboard

Deserializing Map with enum keys results in runtime string keys

Open ivangreene opened this issue 5 years ago • 16 comments

Attempting to deserialize json into a Map with enum keys will result in the instance having String keys at runtime. Using an enum as the value side of a Map works as expected. We should support Map keys with natural string representations in JSON (immediately, enums and UUIDs come to mind, although I'm sure some other types would benefit from this). This is somewhat related to #110, #177 and #253, although those issues have slightly ambiguous behavior since there is no natural representation, other than the JSON-in-JSON string as the key

A simple example:

public class EnumKeyTest {

    public static class Container {
        public Map<Letter, Integer> letterToOrdinal;
        public Map<String, Letter> nameToLetter;
    }

    @Test
    public void shouldHaveEnumKeys() {
        Jsonb jsonb = JsonbBuilder.create();
        Container container = jsonb.fromJson("{\"letterToOrdinal\":{\"B\": 1}, \"nameToLetter\":{\"a\":\"A\"}}", Container.class);
        assert container.nameToLetter.values().iterator().next() instanceof Letter : "value is Letter";
        assert container.nameToLetter.values().iterator().next() == Letter.A : "value == A";
        assert container.letterToOrdinal.keySet().iterator().next() instanceof Letter : "key is letter";
        assert container.letterToOrdinal.keySet().iterator().next() == Letter.B : "key == B";
    }

    enum Letter {
        A, B, C
    }
}

This test will fail on key is letter since the key value is actually a String.

ivangreene avatar Jul 24 '19 22:07 ivangreene