天天看點

java 空字元轉枚舉_java – 傑克遜無法将空字元串值轉換為枚舉

我正在尋找一個友善的解決方案與Jackson(2.8)在反序列化之前/期間篩選出指向空字元串值的字段:

@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)