I am trying to deserialize JSON into a Java POJO using Jackson. The Json looks like
"foo": {
"one": {
"a":1,
"b":"string"
}
"three":{
"a":2
"b":"another"
}
...
}
And the class I want to deserialize into has this field:
public class Myclass {
private Map<MyEnum, MyPojo> foo;
//setter and getter
public static MyPojo {
private int a;
private String b;
}
}
And my enum type looks like this:
public enum MyEnum {
one("data1"),two("data2")
@JsonValue
String data;
EnumAttrib(String data) {
this.data = data;
}
private static Map<String, MyEnum> ENUM_MAP = new HashMap();
static {
for (MyEnum a: MyEnum.values()) {
ENUM_MAP.put(a.data, a);
}
}
@JsonCreator
public static MyEnum fromData(String string) {
return ENUM_MAP.get(string);
}
}
This solution works well as long us the JSON has known keys which are captured by MyEnum. How can I skip certain JSON elements from serialization (in this example "three
"), if it's not defined in MyEnum
You need to enable READ_UNKNOWN_ENUM_VALUES_AS_NULL
which is disabled by default on your ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
When you do this, the result Map
will contain one entry with key equals to null
and value set to JSON
object related with one of unknown fields. If it is not acceptable you need to write custom deserialiser or remove null
key after deserialisation process.
To solve problem with null
key in Map
you can also use EnumMap
in your POJO
:
private EnumMap<MyEnum, MyPojo> foo;
where null
keys are not permitted and will be skipped.
See also:
To solve your requirement, in case you are using Spring Boot
, add this to your application.properties:
spring.jackson.deserialization.READ_UNKNOWN_ENUM_VALUES_AS_NULL=true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With