Skip to content

Commit 45bee0d

Browse files
committed
Support READ_UNKNOWN_ENUM_VALUES_AS_NULL with @JsonCreator
The deserialization feature READ_UNKNOWN_ENUM_VALUES_AS_NULL allows enum values that are not recognised to take a null value when parsed. Before this commit, this deserialization feature did not work whenever an enum had a method marked @JsonCreator, and the enum creator method itself had to choose null in the case of unknown input. With this change, if an enum creator method throws an IllegalArgumentException then this is considered to be an unknown value and (if READ_UNKNOWN_ENUM_VALUES_AS_NULL is active) then null will be used.
1 parent e8c108e commit 45bee0d

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/main/java/com/fasterxml/jackson/databind/deser/std/FactoryBasedEnumDeserializer.java

+6
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,12 @@ public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOEx
134134
return _factory.callOnWith(_valueClass, value);
135135
} catch (Exception e) {
136136
Throwable t = ClassUtil.throwRootCauseIfIOE(e);
137+
138+
if (ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL) &&
139+
t instanceof IllegalArgumentException) {
140+
return null;
141+
}
142+
137143
return ctxt.handleInstantiationProblem(_valueClass, value, t);
138144
}
139145
}

src/test/java/com/fasterxml/jackson/databind/deser/jdk/EnumDeserializationTest.java

+21
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,17 @@ static enum EnumWithDefaultAnnoAndConstructor {
116116
}
117117
}
118118

119+
static enum StrictEnumCreator {
120+
A, B;
121+
122+
@JsonCreator public static StrictEnumCreator fromId(String value) {
123+
for (StrictEnumCreator e: values()) {
124+
if (e.name().toLowerCase().equals(value)) return e;
125+
}
126+
throw new IllegalArgumentException(value);
127+
}
128+
}
129+
119130
// //
120131

121132
public enum AnEnum {
@@ -321,6 +332,16 @@ public void testAllowUnknownEnumValuesReadAsNull() throws Exception
321332
assertNull(reader.forType(TestEnum.class).readValue(" 4343 "));
322333
}
323334

335+
// Ability to ignore unknown Enum values:
336+
337+
public void testAllowUnknownEnumValuesReadAsNullWithCreatorMethod() throws Exception
338+
{
339+
// can not use shared mapper when changing configs...
340+
ObjectReader reader = MAPPER.reader(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
341+
assertNull(reader.forType(StrictEnumCreator.class).readValue("\"NO-SUCH-VALUE\""));
342+
assertNull(reader.forType(StrictEnumCreator.class).readValue(" 4343 "));
343+
}
344+
324345
public void testAllowUnknownEnumValuesForEnumSets() throws Exception
325346
{
326347
ObjectReader reader = MAPPER.reader(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);

0 commit comments

Comments
 (0)