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

如何将JSON字符串转换为Java对象列表?,java,json,jackson,jackson-databind,Java,Json,Jackson,Jackson Databind,这是我的JSON数组:- [ { "firstName" : "abc", "lastName" : "xyz" }, { "firstName" : "pqr", "lastName" : "str" } ] 我的字符串对象中有这个。现在我想把它转换成Java对象并存储在Java对象列表中。e、 g.在学生对象中。 我使用以下代码将其转换为Java对象列表:- ObjectMapper ma

这是我的JSON数组:-

[ 
    {
        "firstName" : "abc",
        "lastName" : "xyz"
    }, 
    {
        "firstName" : "pqr",
        "lastName" : "str"
    } 
]
我的字符串对象中有这个。现在我想把它转换成Java对象并存储在Java对象列表中。e、 g.在学生对象中。 我使用以下代码将其转换为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
}
我是不是遗漏了什么? 我得到以下例外:-

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

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

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

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

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

List<Name> list = nameList.getList();
Gson-Gson=new-Gson();
NameList NameList=gson.fromJson(数据,NameList.class);
List=nameList.getList();
您的名称列表类可能如下所示:

class NameList{
 List<Name> list;
 //getter and setter
}
类名称列表{
名单;
//接二连三
}
把这个换成这个

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

我已经通过创建JSON的POJO类(Student.class)解决了这个问题,Main类用于读取问题中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;
} }
**主类**
公共静态void main(字符串[]args)引发JsonParseException,
JsonMappingException,IOException{
字符串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=新的ObjectMapper();
List details=mapper.readValue(jsonStr,新
TypeReference(){});
对于(学生itr:详细信息){
System.out.println(“getFirstName的值为:”+
itr.getFirstName());
System.out.println(“getLastName的值为:”+
itr.getLastName());
}
}
**结果:**
getFirstName的值为:abc
getLastName的值为:xyz
getFirstName的值为:pqr
getLastName的值为:str
**学生.班级:**
公立班学生{
私有字符串lastName;
私有字符串名;
公共字符串getLastName(){
返回姓氏;
}
公共字符串getFirstName(){
返回名字;
} }

我在下面创建了一个方法,名为
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;
    }
List items=jsonArrayToObjectList(
“domain/ItemsArray.json”,Item.class);
公共静态列表JSONArrayTobjectList(字符串jsonFileName,类tClass)引发IOException{
ObjectMapper mapper=新的ObjectMapper();
最终文件File=ResourceUtils.getFile(“类路径:+jsonFileName”);
CollectionType listType=mapper.getTypeFactory()
.ConstructionCollectionType(ArrayList.class,tClass);
List ts=mapper.readValue(文件,列表类型);
返回ts;
}

试试这个。它对我有用。希望你也一样

List testList=new ArrayList();
testList.add(test1);
Gson Gson=新的Gson();
字符串json=gson.toJson(testList);
Type Type=new-TypeToken(){}.getType();

ArrayList数组=gson.fromJson(json,类型)您可以使用下面的类来读取对象列表。它包含读取具有特定对象类型的列表的静态方法。它包括JDK8模块更改,这些更改也提供了新的时间类支持。它是一个干净的泛型类

List<Student> students = JsonMapper.readList(jsonString, Student.class);
List 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;
    }
}
import com.fasterxml.jackson.databind.DeserializationFeature;
导入com.fasterxml.jackson.databind.ObjectMapper;
导入com.fasterxml.jackson.datatype.jdk8.jdk8模块;
导入com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
导入java.io.IOException;
导入java.util.*;
导入java.util.Collection;
公共类JsonMapper{
公共静态列表readList(字符串str,类类型){
返回readList(str,ArrayList.class,type);
}

公共静态列表readList(String str,Class,适用于任何尚未找到答案的人:

1.将
jackson-databind
库添加到诸如Gradle或Maven之类的构建工具中

2.在代码中:

ObjectMapper mapper = new ObjectMapper();

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

studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
ObjectMapper mapper=new ObjectMapper();
List studentList=new ArrayList();
studentList=Arrays.asList(mapper.readValue(jsonstringaray,Student[].class));

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

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);
String list=“你的字符串”;
Gson Gson=新的Gson();
类型listType=newTypeToken(){}.getType();
ArrayList users=new Gson().fromJson(列表,列表类型);

您正在尝试将
列表
反序列化为
学生
特别是:
mapper.readValue(jsonString,Student.class)
序列化学生,而不是“学生或学生列表(如果json看起来像列表)。”您应该使用@yshavit:-我已经更新了问题。很抱歉。请再次查看。您的JSON看起来不像
{“participantList”:[]
。这就是错误试图告诉您的问题。这里是有效的解决方案。这个解决方案更简单。它使用
TypeToken
classe。虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,只有代码的答案是没有用的。@AlexRiabov添加了上下文。完美答案。总是有效的。但我有一个后续问题。如果学生POJO有一个嵌套的hashmap结构,而jsonString有一个应该映射到这个嵌套hashmap的部分,会怎么样?有人能告诉我如何实现吗?嗯,我理解我试图实现的。我必须更改JSON结构(我有权这样做)。[{“id”:“1”,“name”:“XYZ”,“thisHasToBeHashMap”:{“key1”:“value1”
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;
    }
}
ObjectMapper mapper = new ObjectMapper();

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

studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);