杰克逊反序列化意外令牌(END_OBJECT), [英] Jackson deserialization Unexpected token (END_OBJECT),
问题描述
我正在尝试使用一个Abstact类Animal上的Jackson注释将JSON对象反序列化为Java对象:
I am trying to deserialize a JSON Object into a Java Object using Jackson annotation on one Abstact class "Animal":
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({@Type(value = Dog.class, name = "chien"),
@Type(value = Cat.class, name= "chat")})
和这是一个示例JSON字符串:
and here is a sample JSON string:
{
"name": "Chihuahua",
"type": {
"code": "chien",
"description": "Chien mechant"
}
}
问题是JSON对象中的属性type也是一个对象。当我尝试反序列化我有这个例外:
The problem is that the property "type" in the JSON object is also an object. when i try to deserialize i have this Exception:
Caused by: org.codehaus.jackson.map.JsonMappingException: Could not resolve type id '{' into a subtype of [simple type, class Animal]
我试图使用 type.codeas属性值,但没有。 Exeption就是这个
I tried to use "type.code "as "property" value but nothing. the Exeption is this
Caused by: org.codehaus.jackson.map.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type.code' that is to contain type id (for class Animal)
知道什么是错误。谢谢。
Any idea what's wrong. Thank you.
推荐答案
在找不到解决此问题的方法之后将其扔出去。如果任何偶然发现这一点的人感兴趣,我想出了自己的风格。如果你找到另一种方法,请随意添加自己的解决方案。
Throwing this out there after having found no solution to this problem. I came up with my own style if it interests anyone who stumbles upon this. Feel free to add your own solutions if you find another way.
我已经在我的枚举中实现了解决这个问题的方法是添加一个findByType方法,允许你搜索在枚举键值的字符串表示上。
所以在你的例子中你有一个带有键/值对的枚举,
I have implemented in my enums to fix this problem has been to add a findByType method that allows you to search on a string representation of the enum key value. So in your example you have an enum with a key/value pair as such,
pubilc enum MyEnum {
...
CHIEN("chien", "Chien mechant")
...
}
// Map used to hold mappings between the event key and description
private static final Map<String, String> MY_MAP = new HashMap<String, String>();
// Statically fills the #MY_MAP.
static {
for (final MyEnum myEnum: MyEnum.values()) {
MY_MAP.put(myEnum.getKey(), myEnum);
}
}
然后你会有一个公共方法findByTypeCode返回您搜索的键的类型:
and then you would have a public method findByTypeCode that would return the type for the key you search on:
public static MyEnum findByKey(String pKey) {
final MyEnum match = MY_MAP.get(pKey);
if (match == null) {
throw new SomeNotFoundException("No match found for the given key: " + pKey);
}
return match;
}
我希望这会有所帮助。就像我说的那样,可能有一个解决方案可以直接解决这个问题,但是我没有找到解决方案,并且当这个工作得很好时,不需要浪费更多的时间来寻找解决方案。
I hope this helps. Like I said, there may be a solution out there that tackles this directly, but I haven't found one and don't need to waste more time searching for a solution when this works well enough.
这篇关于杰克逊反序列化意外令牌(END_OBJECT),的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!