杰克逊使用枚举键POJO值反序列化为Map [英] Jackson deserializing into Map with an Enum Key, POJO Value
问题描述
我正在尝试使用Jackson将JSON反序列化为Java POJO.在不泄露机密信息的情况下,这是ObjectMapper的反序列化失败时的示例堆栈跟踪:
I am trying to deserialize JSON into a Java POJO using Jackson. Without giving away confidential information, here is an example stack trace when ObjectMapper's deserialization fails:
org.codehaus.jackson.map.JsonMappingException: Can not construct Map key of type com.example.MyEnum from String "coins": not a valid representation: Can not construct Map key of type com.example.MyEnum from String "coins": not one of values for Enum class
我的JSON看起来像这样:
My JSON looks like this:
"foo": {
"coins": null,
...
}
我要反序列化的类具有以下字段:
And the class I want to deserialize into has this field:
private Map<MyEnum, MyPojo> foo;
我的枚举类型如下:
public enum MyEnum {
COINS("coins"),
...
}
我确实意识到我正在尝试反序列化一个空值.但是我认为这仍然应该起作用:反序列化的结果应该等效于使用foo.put(MyEnum.COINS, null)
映射,这确实是有效的Java指令.非常感谢您的帮助,谢谢.
I do realize that I am trying to deserialize a null value. But I believe this should still work: the result of the deserialization should be equivalent to having a Map with foo.put(MyEnum.COINS, null)
, which is indeed a valid Java instruction. Help is much appreciated, thanks in advance.
推荐答案
除了提供一种好的解决方案(工厂方法)外,还有两种其他方法:
In addition to one good solution presented (factory method), there are 2 other ways:
- 如果'MyEnum.toString()'返回"coins",您可以使用
ObjectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
使Jackson在"name()"上使用"toString()"
- 您可以添加其他方法以返回要使用的id,并用
@JsonValue
注释标记该方法(实际上,您也可以在toString()
上使用该方法,而不是启用上述功能)-如果该注释存在,该方法返回的值用作ID.
- If 'MyEnum.toString()' would return "coins", you can make Jackson use "toString()" over "name()"with
ObjectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
- You could add some other method to return id to use, and mark that method with
@JsonValue
annotation (you can actually use that ontoString()
as well, instead of enabling above feature) -- if that annotation exists, value returned by that method is used as the id.
这篇关于杰克逊使用枚举键POJO值反序列化为Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!