杰克逊无法将空字符串值转换为枚举

时间:2018-07-18 16:22:19

标签: java json jackson2

我正在寻找Jackson(2.8)的便捷解决方案,以在反序列化之前/期间过滤掉指向空String值的字段:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Guis {

public enum Context {
    SDS,
    NAVIGATION
}

public enum Layer {
    Library,
    Status,
    Drivingdata
}

// client code

 String s = "{\"context\":\"\",\"layer\":\"Drivingdata\"}";
 ObjectMapper mapper = new ObjectMapper();
 Guis o = mapper.readValue(s, Guis.class);

错误

 Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type cq.speech.rsi.api.Guis$Context from String "": value not one of declared Enum instance names: [SDS NAVIGATION] at [Source: {"context":"","layer":"Drivingdata"}; line: 1, column: 12] (through reference chain: cq.speech.rsi.api.Guis["context"])

我还尝试了什么... 啊,这个

mapper.getDeserializationConfig().with(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

错误仍然存​​在,显然甚至在谷歌上搜索也无济于事...

编辑

set DeserializationFeature不能如上例所示工作。对我来说,解决方案最终是添加以下代码段:

 mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true)

2 个答案:

答案 0 :(得分:9)

您可以为映射器启用DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL,默认情况下禁用。只是警告使用此方法,它将把包括空字符串在内的所有未知数都视为枚举的null。

答案 1 :(得分:6)

如果字符串与枚举文字不匹配,则可以使用工厂返回空值:

public enum Context {
    SDS,
    NAVIGATION;

    @JsonCreator
    public static Context forName(String name) {
        for(Context c: values()) {
            if(c.name().equals(name)) { //change accordingly
                return c;
            }
        }

        return null;
    }
}

当然可以根据您的逻辑更改实现,但这可以为枚举使用null值。

JsonCreator注释告诉Jackson调用该方法以获取字符串的实例。