Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore JSON deserialization if enum map key is null or unknown

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

like image 753
Kid F Avatar asked Dec 23 '22 00:12

Kid F


2 Answers

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:

  • Jackson deserializing into Map with an Enum Key, POJO Value
like image 107
Michał Ziober Avatar answered Jan 07 '23 11:01

Michał Ziober


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
like image 31
yglodt Avatar answered Jan 07 '23 11:01

yglodt