gpt4 book ai didi

json - Jackson 反序列化意外 token (END_OBJECT),

转载 作者:行者123 更新时间:2023-12-01 06:53:23 25 4
gpt4 key购买 nike

我正在尝试在一个 Abstact 类“Animal”上使用 Jackson 注释将 JSON 对象反序列化为 Java 对象:

@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 字符串:
{
"name": "Chihuahua",
"type": {
"code": "chien",
"description": "Chien mechant"
}
}

问题是 JSON 对象中的属性“type”也是一个对象。当我尝试反序列化时,我有这个异常:
Caused by: org.codehaus.jackson.map.JsonMappingException: Could not resolve type id '{' into a subtype of [simple type, class Animal]

我尝试使用“type.code”作为“属性”值,但没有。异常(exception)是这个
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)

知道有什么问题。谢谢你。

最佳答案

在没有找到解决此问题的方法后将其扔在那里。如果任何偶然发现这一点的人感兴趣,我就会想出我自己的风格。如果您找到其他方法,请随意添加您自己的解决方案。

我在枚举中实现了解决此问题的方法是添加一个 findByType 方法,该方法允许您搜索枚举键值的字符串表示形式。
因此,在您的示例中,您有一个带有键/值对的枚举,

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);
}
}

然后您将拥有一个公共(public)方法 findByTypeCode ,该方法将返回您搜索的键的类型:
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;
}

我希望这有帮助。就像我说的那样,可能有一个直接解决这个问题的解决方案,但我还没有找到一个解决方案,并且当它运行良好时不需要浪费更多时间来寻找解决方案。

关于json - Jackson 反序列化意外 token (END_OBJECT),,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7502972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com