简体   繁体   中英

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

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:

为了满足您的要求,如果您使用的是Spring Boot ,请将其添加到application.properties中:

spring.jackson.deserialization.READ_UNKNOWN_ENUM_VALUES_AS_NULL=true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM