Java 将 JSON 字符串转换为 List - Jackson 库示例
要将 JSON 类型的字符串转换为列表,首先需要使用 JSON 库(如 Jackson、Gson)将 JSON 字符串解析为 Java 对象,然后将解析后的对象转换为列表。
以下是使用 Jackson 库将 JSON 字符串转换为列表的示例代码:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) {
String jsonString = '[{"name":"John","age":30},{"name":"Emily","age":25}]';
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Person> personList = objectMapper.readValue(jsonString, new TypeReference<List<Person>>() {});
for (Person person : personList) {
System.out.println('Name: ' + person.getName());
System.out.println('Age: ' + person.getAge());
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
在上述示例中,我们使用 Jackson 库的 ObjectMapper 类将 JSON 字符串解析为 List<Person> 对象。TypeReference<List<Person>> 用于指定解析的目标类型。最后,我们可以遍历列表并访问每个对象的属性。
请注意,示例中的 Person 类用于表示 JSON 中的每个对象,您可以根据您的需求定义自己的类。
原文地址: https://www.cveoy.top/t/topic/qEWI 著作权归作者所有。请勿转载和采集!