Issue handling unknown/unmapped Enum keys · Issue #1859 · FasterXML/jackson-databind (original) (raw)
Hi,
Trying to deserialize a JSON string using jackson-databind Objectmapper which has a set of Enum attributes within it, but ends up in InvalidFormatException.
This happens when an unknown attribute, which is not defined in the enum comes in the JSON.
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
But, deserialization (objectMapper.readValue(jsonText, .class);) throws an error. "Test" is the unknown attribute that comes in the JSON String to be deserialized.
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize Map key of type com..* from String "Test": not a valid representation, problem:(com.fasterxml.jackson.databind.exc.InvalidFormatException) Cannot deserialize Map key of type com.... from String "Test": not one of values excepted for Enum class: [ ]
Sample of JSON String would look like this.
String jsonText="{\"cartId\":\"31028\",\"userId\":\"106784\",\"attributes\":{\"count\":\"1\",\"amount\":\"10\",\"email\":\"N\",\"Test\":\"No\",\"phone\":\"N\"}}";
The JSON maps to a Cart class, which holds these attributes as a Map.
public class Cart {
private String cartId;
private String userId;
private Map<Attributes,String> attributes;
}
Attributes map to the Enum, as given below.
public enum Attributes {
Count(0),
Amount(1),
Email(2),
Phone(3);
private final int value;
private Attributes(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Also tried adding this configuration
objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
This resulted in the Unknown attribute key to be deserialized as null. (i.e., instead of Test=No, it gets deserialized as null=No). So, when a new attribute - say, 'Test' comes in the Json, it would be good if the mapper can ignore that field and proceed with de-serializing the remaining fields that has a match in the Enum, rather than throwing the exception.