【发布时间】:2019-09-29 08:26:28
【问题描述】:
我正在尝试将 JSON 映射到 ArrayList,但出现“无法从 START_OBJECT 令牌中反序列化 java.util.ArrayList 的实例”错误,我不明白为什么。我找到了这篇文章:Can not deserialize instance of java.util.ArrayList out of START_OBJECT token解决了类似的问题(JSON 无效),但似乎我有有效的 json 文件。我正在使用这个问题中提出的映射方法:How to use Jackson to deserialise an array of objects
我发现这篇文章:Can not deserialize instance of java.util.ArrayList out of START_OBJECT token 解决了类似的问题(JSON 无效),但似乎我有有效的 json 文件。我正在使用这个问题中提出的映射方法:How to use Jackson to deserialise an array of objects
我的 Json 看起来像这样:
[
{
"id": "12345",
"name": "John"
},
{
"id": "09876",
"name": "Desmond"
}
]
数据模型:
public class Student {
private int id;
private String name;
public Student() {}
// getters, setters and tostring
}
解析代码:
ObjectMapper objectMapper = new ObjectMapper();
Path pathToStudentsJson = Paths.get("src/main/resources/static/students.json");
File studentsFile = new File(pathToSingleStudentJson.toString());
List<Student> listOfStudents = objectMapper.readValue(studentsFile, new TypeReference<List<Student>>(){});
我得到的错误:
Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
at [Source: (File); line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1343)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1139)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1093)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:332)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:265)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:27)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2940)
at io.json.JsonApp.main(JsonApp.java:46)
Process finished with exit code 1
【问题讨论】:
-
使用版本2.9.8 可以正常工作。你用的是哪个版本?
-
我也有2.9.8版本!还是一样的错误!
标签: java json arraylist jackson mapping