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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44589381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:37:00  来源:igfitidea点击:

How to convert JSON string into List of Java object?

javajsonHymansonHymanson-databind

提问by Nitesh

This is my JSON Array :-

这是我的 JSON 数组:-

[ 
    {
        "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 : -

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

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.Hymanson.databind.JsonMappingException: Can not deserialize instance of com.aa.Student out of START_ARRAY token

采纳答案by Manos Nikolaidis

You are asking Hymanson to parse a StudentList. Tell it to parse a List(of students) instead. Since Listis generic you will typically use a TypeReference

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

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

回答by Pankaj Jaiswal

You can also use Gson for this scenario.

你也可以在这个场景中使用 Gson。

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

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

Your NameList class could look like:

您的 NameList 类可能如下所示:

class NameList{
 List<Name> list;
 //getter and setter
}

回答by monstereo

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

Change this to this one

把这个改成这个

StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

回答by Atul Sharma

I have resolved this one by creating the POJO class (Student.class) of the JSON and Main Class is used for read the values from the JSON in the problem.

我通过创建 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;
} }

回答by javaPlease42

I made a method to do this below called jsonArrayToObjectList. Its a handy static class that will take a filename and the file contains an array in JSON form.

我在下面创建了一个方法来执行此操作,称为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;
    }

回答by ?ào ??c Huy

Try this. It works with me. Hope you too!

尝试这个。它和我一起工作。希望你也是!

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);

回答by erhun

You can use below class to read list of objects. It contains static method to read a list with some specific object type. It is included Jdk8Module changes which provide new time class supports too. It is a clean and generic class.

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

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

Generic JsonMapper class:

通用 JsonMapper 类:

import com.fasterxml.Hymanson.databind.DeserializationFeature;
import com.fasterxml.Hymanson.databind.ObjectMapper;
import com.fasterxml.Hymanson.datatype.jdk8.Jdk8Module;
import com.fasterxml.Hymanson.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;
    }
}

回答by Sobhan

For any one who looks for answer yet:

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

1.Add Hymanson-databindlibrary to your build tools like Gradle or Maven

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

2.in your Codes:

2.在您的代码中:

 add:
               ObjectMapper mapper = new ObjectMapper();
               List<Student> studentList = new ArrayList<>();

               studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));

回答by Prakash Reddy

use below simple code, no need to use any library

使用下面的简单代码,无需使用任何库

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);