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

问题描述 投票:2回答:2
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

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

java jackson dropwizard
2个回答
0
投票

因为类Babstract class,因此您需要提供可用于实例化B类型的类型。您的情况是C类。您可以通过以下方式指示Jackson执行此操作:

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

或在现场级别:

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

0
投票

这将包含类名作为JSON属性“ class”。

@JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="class")
public abstract class B {
}

public class C extends B {
  public int x;
}
public class D extends B {
  public String name;
}

public class A {
  public List<B> items;
}
and this could result in serialized JSON like:

{ "items" : [
  { "class":"D", "name":"TXT" },
  { "class":"C", "x":123 }
]}

类似的逻辑可用于上述问题,因为我们需要在JSON中使用add some additional info

© www.soinside.com 2019 - 2024. All rights reserved.