Enum default value does not work for map keys · Issue #1674 · FasterXML/jackson-databind (original) (raw)
When using the @JsonEnumDefaultValue
annotation in conjunction with DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE
, unknown enum values that are used as map keys will cause an InvalidFormatException to be thrown. I have verified this in Jackson 2.8.9 and 2.9.0.pr4.
This demonstrates the issue:
package test.jackson;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
public class EnumDefaultValueTest {
private enum TestEnum {VALUE1, VALUE2, @JsonEnumDefaultValue DEFAULT}
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true);
String json = "{\"SOME_UNKNOWN_ENUM\": \"value\"}";
objectMapper.readValue(json, new TypeReference<Map<TestEnum, String>>(){}); //This throws an exception
}
}
The stack trace of the above is:
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize Map key of type test.jackson.EnumDefaultValueTest$TestEnum from String "SOME_UNKNOWN_ENUM": not a valid representation, problem: (com.fasterxml.jackson.databind.exc.InvalidFormatException) Can not deserialize Map key of type test.jackson.EnumDefaultValueTest$TestEnum from String "SOME_UNKNOWN_ENUM": not one of values excepted for Enum class: [VALUE1, VALUE2, DEFAULT]
at [Source: {"SOME_UNKNOWN_ENUM": "value"}; line: 1, column: 2]
at [Source: {"SOME_UNKNOWN_ENUM": "value"}; line: 1, column: 2]
at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:74)
at com.fasterxml.jackson.databind.DeserializationContext.weirdKeyException(DeserializationContext.java:1389)
at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdKey(DeserializationContext.java:880)
at com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer.deserializeKey(StdKeyDeserializer.java:130)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBind(MapDeserializer.java:445)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:365)
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:27)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2877)
at test.jackson.EnumDefaultValueTest.main(EnumDefaultValueTest.java:18)
A workaround is to instead use READ_UNKNOWN_ENUM_VALUES_AS_NULL, which does appear to correctly work with map keys.