我正在尝试将JSON映射到ArrayList,但是我得到了"Cannot and instance of java.util.ArrayList
out of START_OBJECT token“错误,我不明白为什么。我发现了这篇文章: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
发布于 2019-05-12 07:51:28
您的数据模型显示Id是int,而在JSON中是string。尝试更改此设置并使用最新版本的Jackson。它可能会解决这个问题。
发布于 2019-05-12 15:32:44
好了,我找到了我的错误:)它在这里:
Path pathToStudentsJson = Paths.get("src/main/resources/static/students.json");
File studentsFile = new File(pathToSingleStudentJson.toString());
我正在创建引用了不正确路径的文件对象-我应该将pathToStudentsJson而不是pathToSingleStudentJson传递给构造函数
https://stackoverflow.com/questions/56094349
复制相似问题