gpt4 book ai didi

java - com.fasterxml.jackson.databind.JsonMappingException 无法构造类的实例

转载 作者:行者123 更新时间:2023-12-01 21:58:55 24 4
gpt4 key购买 nike

import javax.ws.rs.core.Response;

class A{
@JsonProperty("B")
List<B> b;
@JsonProperty("abc")
String abc;
}

public abstract class B{
@JsonProperty("def")
String def;
}

public class C extends B{
@JsonProperty("xyz")
String xyz;
}

json:

{
"B": [
{
"def": "<text1>"
},
{
"def": "<text1>",
"xyz": "<text2>"
}
],
"abc": "<text3>"
}

响应包含上述json内容

A a  = response.readEntity(A.class);

错误:

javax.ws.rs.client.ResponseProcessingException:` Problem with reading the data, class A, ContentType: application/json.
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of B: abstract types either need to be mapped

有什么方法可以创建包含抽象类对象的类实例吗?

最佳答案

因为类 B 是一个 abstract class 你需要提供可用于实例化 B 的类型类型。在你的例子中是类C。您可以通过以下方式指示 Jackson 执行此操作:

@JsonDeserialize(as = C.class)
abstract class B {

或在字段级别:

@JsonProperty("B")
@JsonDeserialize(contentAs = C.class)
private List<B> b;

关于java - com.fasterxml.jackson.databind.JsonMappingException 无法构造类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60667392/

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