如何将 JSON 字符串转换为 Java 对象列表?
How to convert JSON string into List of Java object?
这是我的 JSON 数组:-
[
{
"firstName" : "abc",
"lastName" : "xyz"
},
{
"firstName" : "pqr",
"lastName" : "str"
}
]
我的字符串对象中有这个。现在我想将其转换为 Java 对象并将其存储在 java 对象的列表中。例如在学生对象中。
我正在使用下面的代码将其转换为 Java 对象列表:-
ObjectMapper mapper = new ObjectMapper();
StudentList studentList = mapper.readValue(jsonString, StudentList.class);
我的列表 class 是:-
public class StudentList {
private List<Student> participantList = new ArrayList<Student>();
//getters and setters
}
我的 Student 对象是:-
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
您要求 Jackson 解析 StudentList
。告诉它改为解析 List
(学生)。由于 List
是通用的,您通常会使用 TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
这个场景也可以使用Gson。
Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);
List<Name> list = nameList.getList();
您的 NameList class 可能如下所示:
class NameList{
List<Name> list;
//getter and setter
}
StudentList studentList = mapper.readValue(jsonString,StudentList.class);
改成这个
StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
我已经通过创建 JSON 的 POJO class (Student.class) 解决了这个问题,Main 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;
} }
我在下面创建了一个名为 jsonArrayToObjectList
的方法来执行此操作。它是一个方便的静态 class,它将采用一个文件名,并且该文件包含一个 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<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);
您可以使用下面的 class 来阅读对象列表。它包含静态方法来读取具有某些特定对象类型的列表。它包含 Jdk8Module 更改,它也提供新的时间 class 支持。这是一个干净而通用的 class.
List<Student> students = JsonMapper.readList(jsonString, Student.class);
通用 JsonMapper class:
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;
}
}
对于任何正在寻找答案的人:
1.Add jackson-databind
库到您的构建工具,如 Gradle 或 Maven
2.in 您的代码:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
使用下面的简单代码,不需要使用任何其他库,除了 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);
这是我的 JSON 数组:-
[
{
"firstName" : "abc",
"lastName" : "xyz"
},
{
"firstName" : "pqr",
"lastName" : "str"
}
]
我的字符串对象中有这个。现在我想将其转换为 Java 对象并将其存储在 java 对象的列表中。例如在学生对象中。 我正在使用下面的代码将其转换为 Java 对象列表:-
ObjectMapper mapper = new ObjectMapper();
StudentList studentList = mapper.readValue(jsonString, StudentList.class);
我的列表 class 是:-
public class StudentList {
private List<Student> participantList = new ArrayList<Student>();
//getters and setters
}
我的 Student 对象是:-
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
您要求 Jackson 解析 StudentList
。告诉它改为解析 List
(学生)。由于 List
是通用的,您通常会使用 TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
这个场景也可以使用Gson。
Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);
List<Name> list = nameList.getList();
您的 NameList class 可能如下所示:
class NameList{
List<Name> list;
//getter and setter
}
StudentList studentList = mapper.readValue(jsonString,StudentList.class);
改成这个
StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
我已经通过创建 JSON 的 POJO class (Student.class) 解决了这个问题,Main 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;
} }
我在下面创建了一个名为 jsonArrayToObjectList
的方法来执行此操作。它是一个方便的静态 class,它将采用一个文件名,并且该文件包含一个 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<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);
您可以使用下面的 class 来阅读对象列表。它包含静态方法来读取具有某些特定对象类型的列表。它包含 Jdk8Module 更改,它也提供新的时间 class 支持。这是一个干净而通用的 class.
List<Student> students = JsonMapper.readList(jsonString, Student.class);
通用 JsonMapper class:
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;
}
}
对于任何正在寻找答案的人:
1.Add jackson-databind
库到您的构建工具,如 Gradle 或 Maven
2.in 您的代码:
ObjectMapper mapper = new ObjectMapper();
List<Student> studentList = new ArrayList<>();
studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
使用下面的简单代码,不需要使用任何其他库,除了 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);