要将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中的每个对象,您可以根据您的需求定义自己的类

java json类型的string 转换成list

原文地址: https://www.cveoy.top/t/topic/iYUD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录