Jackson Exceptions – Problems and Solutions
最后更新:2024年4月8日
1. 概述
在本教程中,我们将介绍最常见的 Jackson Exceptions — JsonMappingException, UnrecognizedPropertyException, 和 MismatchedInputException。
最后,我们将简要讨论 Jackson “No such method” 错误。
更多阅读
2. JsonMappingException: Cannot Construct Instance Of
2.1. The Problem
首先,我们来看一下 JsonMappingException: Cannot Construct Instance Of。
如果 Jackson 无法创建类的实例,则会抛出此异常,这发生在类是抽象类或只是一个接口的情况下。
这里我们将尝试从具有abstract 类型属性animal 的类Zoo 中反序列化一个实例Animal
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() { }
}
当我们尝试将 JSON String 反序列化为 Zoo 实例时,它会抛出 JsonMappingException: Cannot 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)
2.2. Solutions
我们可以使用一个简单的注解来解决问题 — @JsonDeserialize 在抽象类上
@JsonDeserialize(as = Cat.class)
abstract class Animal {...}
请注意,如果抽象类有多个子类型,我们应该考虑包含子类型信息,如文章 Inheritance With Jackson 中所示。
3. JsonMappingException: No Suitable Constructor
3.1. The Problem
现在我们来看看常见的 JsonMappingException: No Suitable Constructor found for type。
如果 Jackson 无法访问构造函数,则会抛出此异常。
在下面的例子中,类User 没有默认构造函数
public class User {
public int id;
public String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
当我们尝试将 JSON String 反序列化为 User 时,JsonMappingException: No Suitable Constructor Found 被抛出
@Test(expected = JsonMappingException.class)
public void givenNoDefaultConstructor_whenDeserializing_thenException()
throws IOException {
String json = "{"id":1,"name":"John"}";
ObjectMapper mapper = new ObjectMapper();
mapper.reader().forType(User.class).readValue(json);
}
这是完整的异常
com.fasterxml.jackson.databind.JsonMappingException:
No suitable constructor found for type
[simple type, class org.baeldung.jackson.exception.User]:
can not instantiate from JSON object (need to add/enable type information?)
at [Source: {"id":1,"name":"John"}; line: 1, column: 2]
at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)
3.2. The Solution
为了解决这个问题,我们只需添加一个默认构造函数
public class User {
public int id;
public String name;
public User() {
super();
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
现在当我们反序列化时,该过程将正常工作
@Test
public void givenDefaultConstructor_whenDeserializing_thenCorrect()
throws IOException {
String json = "{"id":1,"name":"John"}";
ObjectMapper mapper = new ObjectMapper();
User user = mapper.reader()
.forType(User.class).readValue(json);
assertEquals("John", user.name);
}
4. JsonMappingException: Root Name Does Not Match Expected
4.1. The Problem
接下来,我们来看一下 JsonMappingException: Root Name Does Not Match Expected。
如果 JSON 与 Jackson 查找的内容不完全匹配,则会抛出此异常。
例如,主 JSON 可能是被包裹的
@Test(expected = JsonMappingException.class)
public void givenWrappedJsonString_whenDeserializing_thenException()
throws IOException {
String json = "{"user":{"id":1,"name":"John"}}";
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.reader().forType(User.class).readValue(json);
}
这是完整的异常
com.fasterxml.jackson.databind.JsonMappingException:
Root name 'user' does not match expected ('User') for type
[simple type, class org.baeldung.jackson.dtos.User]
at [Source: {"user":{"id":1,"name":"John"}}; line: 1, column: 2]
at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)
4.2. The Solution
我们可以使用注解@JsonRootName 来解决这个问题
@JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
}
当我们尝试反序列化被包裹的 JSON 时,它就可以正常工作了
@Test
public void
givenWrappedJsonStringAndConfigureClass_whenDeserializing_thenCorrect()
throws IOException {
String json = "{"user":{"id":1,"name":"John"}}";
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
UserWithRoot user = mapper.reader()
.forType(UserWithRoot.class)
.readValue(json);
assertEquals("John", user.name);
}
5. JsonMappingException: No Serializer Found for Class
5.1. The Problem
现在我们来看看 JsonMappingException: No Serializer Found for Class。
如果在尝试序列化一个实例,而其属性及其 getter 是私有的,则会抛出此异常。
我们将尝试序列化一个UserWithPrivateFields
public class UserWithPrivateFields {
int id;
String name;
}
当我们尝试序列化UserWithPrivateFields 的实例时,JsonMappingException: No Serializer Found for Class 被抛出
@Test(expected = JsonMappingException.class)
public void givenClassWithPrivateFields_whenSerializing_thenException()
throws IOException {
UserWithPrivateFields user = new UserWithPrivateFields(1, "John");
ObjectMapper mapper = new ObjectMapper();
mapper.writer().writeValueAsString(user);
}
这是完整的异常
com.fasterxml.jackson.databind.JsonMappingException:
No serializer found for class org.baeldung.jackson.exception.UserWithPrivateFields
and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
at c.f.j.d.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
5.2. The Solution
我们可以通过配置ObjectMapper 的可见性来解决这个问题
@Test
public void givenClassWithPrivateFields_whenConfigureSerializing_thenCorrect()
throws IOException {
UserWithPrivateFields user = new UserWithPrivateFields(1, "John");
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
String result = mapper.writer().writeValueAsString(user);
assertThat(result, containsString("John"));
}
或者我们可以使用注解@JsonAutoDetect
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class UserWithPrivateFields { ... }
当然,如果我们有机会修改类的源代码,我们也可以添加 getter,供 Jackson 使用。
6. JsonMappingException: Can Not Deserialize Instance Of
6.1. The Problem
接下来,我们来看看 JsonMappingException: Can Not Deserialize Instance Of。
如果在使用反序列化时使用了错误类型,则会抛出此异常。
在本例中,我们正在尝试反序列化一个User 的List
@Test(expected = JsonMappingException.class)
public void givenJsonOfArray_whenDeserializing_thenException()
throws JsonProcessingException, IOException {
String json
= "[{"id":1,"name":"John"},{"id":2,"name":"Adam"}]";
ObjectMapper mapper = new ObjectMapper();
mapper.reader().forType(User.class).readValue(json);
}
这是完整的异常
com.fasterxml.jackson.databind.JsonMappingException:
Can not deserialize instance of
org.baeldung.jackson.dtos.User out of START_ARRAY token
at [Source: [{"id":1,"name":"John"},{"id":2,"name":"Adam"}]; line: 1, column: 1]
at c.f.j.d.JsonMappingException.from(JsonMappingException.java:148)
6.2. The Solution
我们可以通过将类型从 User 更改为 List<User> 来解决这个问题
@Test
public void givenJsonOfArray_whenDeserializing_thenCorrect()
throws JsonProcessingException, IOException {
String json
= "[{"id":1,"name":"John"},{"id":2,"name":"Adam"}]";
ObjectMapper mapper = new ObjectMapper();
List<User> users = mapper.reader()
.forType(new TypeReference<List<User>>() {})
.readValue(json);
assertEquals(2, users.size());
}
7. JsonMappingException: 无法从 Object 值反序列化类型为 java.lang.String 的值
在深入细节之前,让我们先尝试理解这个异常意味着什么。
该异常的堆栈跟踪说明了一切:“Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)”。 这意味着 Jackson 无法将一个对象反序列化为 String 实例。
7.1. 重现异常
此异常最常见的原因是将 JSON 对象映射到 String 实例。
例如,让我们考虑 Person 类
public class Person {
private String firstName;
private String lastName;
private String contact;
// standard getters and setters
}
如上所示,我们声明了 contact 字段的类型为 String。
现在,让我们看看如果反序列化此 JSON 字符串会发生什么
{
"firstName":"Azhrioun",
"lastName":"Abderrahim",
"contact":{
"email":"[email protected]"
}
}
Jackson 出现堆栈跟踪错误
Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
at [Source: (String)"{"firstName":"Azhrioun","lastName":"Abderrahim","contact":{"email":"[email protected]"}}"; line: 1, column: 59] (through reference chain: com.baeldung.exceptions.Person["contact"])
...
让我们使用一个测试用例来确认这一点
@Test
public void givenJsonObject_whenDeserializingIntoString_thenException() throws IOException {
final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"[email protected]\"}}";
final ObjectMapper mapper = new ObjectMapper();
Exception exception = assertThrows(JsonMappingException.class, () -> mapper.reader()
.forType(Person.class)
.readValue(json));
assertTrue(exception.getMessage()
.contains("Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)"));
}
正如我们所见,我们试图将 JSON 对象: “contact”:{“email”: “[email protected]”}}” 反序列化到 contact 属性,而该属性是 String。因此出现异常。
7.2. 解决方案
最简单的解决方案是将每个 JSON 对象映射到 Java 对象,而不是简单的 String 对象.
所以,让我们创建一个类 Contact 来表示 JSON 对象“contact”:{“email”: “[email protected]”}}”
public class Contact {
private String email;
// standard getter and setter
}
接下来,让我们重写 Person 类,将 contact 类型从 String 更改为 Contact
public class PersonContact {
private String firstName;
private String lastName;
private Contact contact;
// standard getters and setters
}
现在,我们将添加另一个测试用例来验证一切是否按预期工作
@Test
public void givenJsonObject_whenDeserializingIntoObject_thenDeserialize() throws IOException {
final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"[email protected]\"}}";
final ObjectMapper mapper = new ObjectMapper();
PersonContact person = mapper.reader()
.forType(PersonContact.class)
.readValue(json);
assertEquals("[email protected]", person.getContact().getEmail());
}
8. UnrecognizedPropertyException
8.1. 问题
现在让我们看看 UnrecognizedPropertyException。
在反序列化时,如果 JSON String 中存在未知的属性,则会抛出此异常。
我们将尝试反序列化一个包含额外属性 “checked“ 的 JSON String
@Test(expected = UnrecognizedPropertyException.class)
public void givenJsonStringWithExtra_whenDeserializing_thenException()
throws IOException {
String json = "{"id":1,"name":"John", "checked":true}";
ObjectMapper mapper = new ObjectMapper();
mapper.reader().forType(User.class).readValue(json);
}
这是完整的异常
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
Unrecognized field "checked" (class org.baeldung.jackson.dtos.User),
not marked as ignorable (2 known properties: "id", "name"])
at [Source: {"id":1,"name":"John", "checked":true}; line: 1, column: 38]
(through reference chain: org.baeldung.jackson.dtos.User["checked"])
at c.f.j.d.exc.UnrecognizedPropertyException.from(
UnrecognizedPropertyException.java:51)
8.2. 解决方案
我们可以通过配置 ObjectMapper 来解决这个问题
@Test
public void givenJsonStringWithExtra_whenConfigureDeserializing_thenCorrect()
throws IOException {
String json = "{"id":1,"name":"John", "checked":true}";
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
User user = mapper.reader().forType(User.class).readValue(json);
assertEquals("John", user.name);
}
或者我们可以使用注解 @JsonIgnoreProperties
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {...}
9. JsonParseException: 意外字符 (”’ (代码 39))
9.1. 问题
接下来,我们来讨论 JsonParseException: Unexpected character (”’ (code 39))。
如果要反序列化的 JSON String 包含单引号而不是双引号,则会抛出此异常。
我们将尝试反序列化一个包含单引号的 JSON String
@Test(expected = JsonParseException.class)
public void givenStringWithSingleQuotes_whenDeserializing_thenException()
throws JsonProcessingException, IOException {
String json = "{'id':1,'name':'John'}";
ObjectMapper mapper = new ObjectMapper();
mapper.reader()
.forType(User.class).readValue(json);
}
这是完整的异常
com.fasterxml.jackson.core.JsonParseException:
Unexpected character (''' (code 39)):
was expecting double-quote to start field name
at [Source: {'id':1,'name':'John'}; line: 1, column: 3]
at c.f.j.core.JsonParser._constructError(JsonParser.java:1419)
9.2. 解决方案
我们可以通过配置 ObjectMapper 以允许单引号来解决这个问题
@Test
public void
givenStringWithSingleQuotes_whenConfigureDeserializing_thenCorrect()
throws JsonProcessingException, IOException {
String json = "{'id':1,'name':'John'}";
JsonFactory factory = new JsonFactory();
factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
ObjectMapper mapper = new ObjectMapper(factory);
User user = mapper.reader().forType(User.class)
.readValue(json);
assertEquals("John", user.name);
}
10. JsonParseException: 意外字符 (‘c’ (代码 n))
在本节中,我们将解决另一个常见的解析异常,JsonParseException: Unexpected character (‘c’ (code n))。当 JSON 解析器在解析过程中遇到意外字符时,会发生此异常。 异常消息中指出了具体的意外字符(‘c’)及其 Unicode 码点(‘n’)。
10.1. 问题
JsonParseException: Unexpected character (‘c’ (code n)) 异常通常是由于 JSON 字符串中存在语法错误或无效字符引起的。这些错误可能是由各种问题引起的,例如缺少逗号、JSON 对象或数组的嵌套不正确,或存在 JSON 语法中不允许的字符。
让我们尝试反序列化一个 JSON 字符串,该字符串在‘name’ 字段周围缺少双引号
@Test(expected = JsonParseException.class)
public void givenInvalidJsonString_whenDeserializing_thenException() throws JsonProcessingException, IOException {
String json = "{\"id\":1, name:\"John\"}"; // Missing double quotes around 'name'
ObjectMapper mapper = new ObjectMapper();
mapper.reader().forType(User.class).readValue(json);
}
这是完整的异常
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('n' (code 110)):
was expecting double-quote to start field name
at [Source: (String)"{"id":1, name:"John"}"; line: 1, column: 11]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:2477)
10.2. 解决方案
要解决JsonParseException: Unexpected character (‘c’ (code n)) 异常,必须仔细检查 JSON 字符串是否存在语法错误,并确保其符合 JSON 规范。
常见的解决方案包括更正语法错误,例如缺少或放置错误的逗号、确保对象和数组的正确嵌套,以及删除 JSON 语法中不允许的任何字符。
11. MismatchedInputException: 无法反序列化实例
MismatchedInputException 异常有不同的变体。当未为 POJO 类提供默认构造函数,或者未用 @JsonProperty 注解不可变字段的构造函数参数时,可能会发生此异常。
此外,如果我们将不兼容的 JSON 数组反序列化为 Java 对象,也可能发生此异常。
11.1. 问题:缺少默认构造函数
当尝试将 JSON 字符串反序列化为没有默认或无参数构造函数的 POJO 类时,会发生此异常。由于 Jackson 需要实例化目标类,因此缺少默认构造函数将导致异常。
为了演示此异常,让我们创建一个名为 Book 的类
class Book {
private int id;
private String title;
public Book(int id, String title) {
this.id = id;
this.title = title;
}
// getters and setters
}
这里,我们创建一个没有默认构造函数的 POJO 类。
接下来,让我们将 JSON 字符串映射到 POJO 类
@Test
void givenJsonString_whenDeserializingToBook_thenIdIsCorrect() throws JsonProcessingException {
String jsonString = "{\"id\":\"10\",\"title\":\"Harry Potter\"}";
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(jsonString, Book.class);
assertEquals(book.getId(),10);
}
上面的测试会抛出 MismatchedInputException
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of `com.baeldung.mismatchedinputexception.Book` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"id":"10","title":"Harry Potter"}"; line: 1, column: 2]
11.2. 解决方案
让我们通过向 Book 类添加默认构造函数来解决此问题
// ...
public Book() {
}
// ...
引入默认构造函数后,现在可以成功运行之前产生错误的测试。
11.3. 问题:缺少 @JsonProperty 注解
如果字段在声明时未初始化,则具有标记为 final 的字段的 POJO 类不能具有默认构造函数。这是因为 final 字段必须通过构造函数或在声明时直接设置。
由于没有默认构造函数,将 JSON 反序列化到类实例时会失败,并出现 MismachedInputException。
让我们创建一个名为 Animal 的 POJO 类,其中包含一个不可变字段
class Animals {
private final int id;
private String name;
public Animals(int id, String name) {
this.id = id;
this.name = name;
}
}
然后,让我们将 JSON 字符串映射到 POJO 类
@Test
void givenJsonString_whenDeserializingToJavaObjectWithImmutableField_thenIdIsCorrect() throws JsonProcessingException {
String jsonString = "{\"id\":10,\"name\":\"Dog\"}";
ObjectMapper mapper = new ObjectMapper();
Animals animal = mapper.readValue(jsonString, Animals.class);
assertEquals(animal.getId(),10);
}
这里,我们断言 id 等于预期的 id。但是,这会抛出一个异常
com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of `com.baeldung.mismatchedinputexception.Animals` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"id":10,"name":"Dog"}"; line: 1, column: 2]
11.4. 解决方案
我们可以通过用 @JsonProperty 注解参数来解决此问题
Animals(@JsonProperty("id") int id, @JsonProperty("name") String name) {
this.id = id;
this.name = name;
}
11.5. 问题:不兼容的 Java 对象
此外,当 Jackson 尝试将 JSON 数组反序列化为不兼容的 Java 对象时,也会发生此错误。
为了引发此错误,让我们使用之前创建的 Book 类,并将 JSON 数组传递到单个 Book 对象
@Test
void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException {
String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]";
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(jsonString, Book.class);
assertEquals(book.getTitle(),"Harry Potter");
}
在上面的代码中,我们将 JSON 数组映射到单个对象。这会抛出一个异常
com.fasterxml.jackson.databind.exc.MismatchedInputException:
Cannot deserialize value of type `com.baeldung.mismatchedinputexception.Book` from Array value (token `JsonToken.START_ARRAY`)
at [Source: (String)"[{"id":"10","title":"Harry Potter"}]"; line: 1, column: 1]
11.6. 解决方案
让我们通过将 JSON 数组反序列化到 List 对象中来解决此问题
@Test
void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException {
String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]";
ObjectMapper mapper = new ObjectMapper();
List<Book> book = mapper.readValue(jsonString, new TypeReference<List<Book>>(){});
assertEquals(book.get(0).getTitle(),"Harry Potter");
}
但是,我们的意图可能是反序列化单个 JSON 字符串而不是 JSON 数组。 我们可以从 jsonString 中删除方括号,并将其映射到单个 Java 对象。
12. Jackson NoSuchMethodError
最后,让我们快速讨论 Jackson“No such method”错误。
当抛出 java.lang.NoSuchMethodError 异常时,通常是因为我们的类路径上有多个(不兼容)版本的 Jackson jar。
这是完整的异常
java.lang.NoSuchMethodError:
com.fasterxml.jackson.core.JsonParser.getValueAsString()Ljava/lang/String;
at c.f.j.d.deser.std.StringDeserializer.deserialize(StringDeserializer.java:24)
13. 结论
在本文中,我们深入研究了 最常见的 Jackson 问题——异常和错误,探讨了潜在原因和针对每个问题的解决方案。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















