Home > Java > javaTutorial > How to convert JSONArray to List in Java

How to convert JSONArray to List in Java

WBOY
Release: 2023-05-04 17:25:06
forward
15397 people have browsed it

1: JSONArray to List

JSONArray string to List

//初始化JSONArray
JSONArray array=new JSONArray();
array.add(0,"a");
array.add(1,"b");
array.add(2,"c");
 
List<String> list = JSONObject.parseArray(array.toJSONString(),String.class);
 
System.out.println(list.toString());
Copy after login

Output result:
[a, b, c]

JSONArray object to List

//初始化JSONArray
JSONArray jsonArray = JSONArray.parseArray("[{\"name\":\"zhangsan\",\"age\":18},{\"name\":\"lisi\",\"age\":23}]");
//打印jsonArray
System.out.println(jsonArray.toJSONString());
//转List
List<Body> list = JSONArray.parseArray(jsonArray.toJSONString(), Body.class);
//打印List<Body>
System.out.println(list.toString());
Copy after login

Body.class code:

/**
*测试实体类
**/
static class Body implements Serializable {
        private static final long serialVersionUID = 1L;
        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;
        }
 
        @Override
        public String toString() {
            return "Body{" +
                    "name=&#39;" + name + &#39;\&#39;&#39; +
                    ", age=" + age +
                    &#39;}&#39;;
        }
}
Copy after login

Output result:
[{"name":"zhangsan","age":18}, {"name":"lisi","age":23}]
[Body{name='zhangsan', age=18}, Body{name='lisi', age=23}]

2: List to JSONArray

List<T> list = new ArrayList<T>();
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
Copy after login

The above is the detailed content of How to convert JSONArray to List in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template