如何将 JSON 字符串转换为 Java 对象列表? [英] How to convert JSON string into List of Java object?
问题描述
这是我的 JSON 数组:-
<预><代码>[{"firstName": "abc",姓氏":xyz"},{"firstName": "pqr",姓氏":str"}]我的 String 对象中有这个.现在我想将它转换为 Java 对象并将其存储在 Java 对象列表中.例如在学生对象中.我正在使用以下代码将其转换为 Java 对象列表:-
ObjectMapper mapper = new ObjectMapper();StudentList studentList = mapper.readValue(jsonString, StudentList.class);
我的列表类是:-
public class StudentList {私人名单<学生>参与者列表 = 新的 ArrayList();//getter 和 setter}
我的学生对象是:-
class 学生 {字符串名字;字符串姓氏;//getter 和 setter}
我在这里遗漏了什么吗?我遇到以下异常:-
异常:com.fasterxml.jackson.databind.JsonMappingException:无法从 START_ARRAY 令牌中反序列化 com.aa.Student 的实例
您要求 Jackson 解析 StudentList
.告诉它解析一个List
(学生).由于 List
是通用的,您通常会使用 类型参考
列表<学生>参与者JsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
This is my JSON Array :-
[
{
"firstName" : "abc",
"lastName" : "xyz"
},
{
"firstName" : "pqr",
"lastName" : "str"
}
]
I have this in my String object. Now I want to convert it into Java object and store it in List of java object. e.g. In Student object. I am using below code to convert it into List of Java object : -
ObjectMapper mapper = new ObjectMapper();
StudentList studentList = mapper.readValue(jsonString, StudentList.class);
My List class is:-
public class StudentList {
private List<Student> participantList = new ArrayList<Student>();
//getters and setters
}
My Student object is: -
class Student {
String firstName;
String lastName;
//getters and setters
}
Am I missing something here? I am getting below exception: -
Exception : com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.aa.Student out of START_ARRAY token
You are asking Jackson to parse a StudentList
. Tell it to parse a List
(of students) instead. Since List
is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
这篇关于如何将 JSON 字符串转换为 Java 对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!