本文翻译自:https://www.baeldung.com/jackson-exception
1,“JsonMappingException: Can not construct instance of”
造成这种异常的原因是 Jackson 无法创建抽象类和接口的实例。
如下面的例子所示:
public class Zoo {
public Animal animal;
public Zoo() { }
}
abstract class Animal {
public String name;
public Animal() { }
}
class Cat extends Animal {
public int lives;
public Cat() { }
}
Zoo 类中含有1个 抽象类 Animal。
当我们将1个 JSON 字符串反序列化成 Zoo 实例的时候,就会抛出JsonMappingException: Can not construct instance of异常:
@Test(expected = JsonMappingException.class)
public void givenAbstractClass_whenDeserializing_thenException()
throws IOException {
String json = "{"animal":{"name":"lacy"}}";
ObjectMapper mapper = new ObjectMapper();
mapper.reader().forType(Zoo.class).readValue(json);
}
异常内容为:
com.fasterxml.jackson.databind.JsonMappingException:
Can not construct instance of org.baeldung.jackson.exception.Animal,
problem: abstract types either need to be mapped to concrete types,
have custom deserializer,
or be instantiated with additional type information
at
[Source: {"animal":{"name":"lacy"}}; line: 1, column: 2]
(through reference chain: org.baeldung.jackson.exception.Zoo["animal"])
at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)