如何将JSON字符串转换为Java对象的列表?

如何将JSON字符串转换为Java对象的列表?

问题描述:

这是我的JSON数组: -

This is my JSON Array :-

[ 
    {
        "firstName" : "abc",
        "lastName" : "xyz"
    }, 
    {
        "firstName" : "pqr",
        "lastName" : "str"
    } 
]

我的String对象中有这个。现在我想将其转换为Java对象并将其存储在Java对象的List中。例如在Student对象中。
我使用下面的代码将其转换为Java对象列表: -

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


您要求Jackson解析 StudentList 。告诉它解析一个 List (学生)。由于 List 是通用的,您通常会使用 TypeReference

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>>(){});