66

这是我的 JSON 数组:-

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

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

ObjectMapper mapper = new ObjectMapper();
StudentList studentList = mapper.readValue(jsonString, StudentList.class);

我的列表类是:-

public class StudentList {

    private List<Student> participantList = new ArrayList<Student>();

    //getters and setters
}

我的学生对象是:-

class Student {

    String firstName;
    String lastName;

    //getters and setters
}

我在这里错过了什么吗?我遇到了以下异常:-

Exception : com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.aa.Student out of START_ARRAY token
4

9 回答 9

131

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

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
于 2017-06-16T12:37:40.333 回答
6

对于任何正在寻找答案的人:

1.将jackson-databind库添加到您的构建工具,如 Gradle 或 Maven

2.在您的代码中:

ObjectMapper mapper = new ObjectMapper();

List<Student> studentList = new ArrayList<>();

studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
于 2020-03-01T12:10:43.547 回答
5

您也可以在这种情况下使用 Gson。

Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);

List<Name> list = nameList.getList();

您的 NameList 类可能如下所示:

class NameList{
 List<Name> list;
 //getter and setter
}
于 2018-06-18T06:28:02.487 回答
3

您可以使用下面的类来读取对象列表。它包含读取具有某些特定对象类型的列表的静态方法。它包含 Jdk8Module 更改,也提供了新的时间类支持。这是一个干净和通用的类。

List<Student> students = JsonMapper.readList(jsonString, Student.class);

通用 JsonMapper 类:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.util.*;

import java.util.Collection;

public class JsonMapper {

    public static <T> List<T> readList(String str, Class<T> type) {
        return readList(str, ArrayList.class, type);
    }

    public static <T> List<T> readList(String str, Class<? extends Collection> type, Class<T> elementType) {
        final ObjectMapper mapper = newMapper();
        try {
            return mapper.readValue(str, mapper.getTypeFactory().constructCollectionType(type, elementType));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static ObjectMapper newMapper() {
        final ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(new Jdk8Module());
        return mapper;
    }
}
于 2019-11-20T17:14:10.533 回答
1
StudentList studentList = mapper.readValue(jsonString,StudentList.class);

把这个改成这个

StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
于 2018-12-10T10:57:45.780 回答
1

我在下面做了一个方法来做到这一点,称为jsonArrayToObjectList. 它是一个方便的静态类,它将接受一个文件名,并且该文件包含一个 JSON 格式的数组。

 List<Items> items = jsonArrayToObjectList(
            "domain/ItemsArray.json",  Item.class);

    public static <T> List<T> jsonArrayToObjectList(String jsonFileName, Class<T> tClass) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        final File file = ResourceUtils.getFile("classpath:" + jsonFileName);
        CollectionType listType = mapper.getTypeFactory()
            .constructCollectionType(ArrayList.class, tClass);
        List<T> ts = mapper.readValue(file, listType);
        return ts;
    }
于 2019-08-22T23:20:12.803 回答
1

使用下面的简单代码,不需要使用任何其他库,除了 GSON

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);
于 2020-03-03T10:25:17.203 回答
0

我通过创建 JSON 的 POJO 类 (Student.class) 解决了这个问题,主类用于从问题中的 JSON 读取值。

   **Main Class**

    public static void main(String[] args) throws JsonParseException, 
       JsonMappingException, IOException {

    String jsonStr = "[ \r\n" + "    {\r\n" + "        \"firstName\" : \"abc\",\r\n"
            + "        \"lastName\" : \"xyz\"\r\n" + "    }, \r\n" + "    {\r\n"
            + "        \"firstName\" : \"pqr\",\r\n" + "        \"lastName\" : \"str\"\r\n" + "    } \r\n" + "]";

    ObjectMapper mapper = new ObjectMapper();

    List<Student> details = mapper.readValue(jsonStr, new 
      TypeReference<List<Student>>() {      });

    for (Student itr : details) {

        System.out.println("Value for getFirstName is: " + 
                  itr.getFirstName());
        System.out.println("Value for getLastName  is: " + 
                 itr.getLastName());
    }
}

**RESULT:**
         Value for getFirstName is: abc
         Value for getLastName  is: xyz
         Value for getFirstName is: pqr
         Value for getLastName  is: str


 **Student.class:**

public class Student {
private String lastName;

private String firstName;

public String getLastName() {
    return lastName;
}

public String getFirstName() {
    return firstName;
} }
于 2018-12-28T06:24:26.973 回答
-1

尝试这个。它对我有用。也希望你!

List<YOUR_OBJECT> testList = new ArrayList<>();
testList.add(test1);

Gson gson = new Gson();

String json = gson.toJson(testList);

Type type = new TypeToken<ArrayList<YOUR_OBJECT>>(){}.getType();

ArrayList<YOUR_OBJECT> array = gson.fromJson(json, type);

于 2019-11-15T06:21:07.693 回答