1、JSONArray转List
JSONArray字符串 转 List
1 2 3 4 5 6 7 8 9 | //初始化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()); |
输出结果:
[a, b, c]
JSONArray对象 转 List
1 2 3 4 5 6 7 8 | //初始化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()); |
Body.class代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** *测试实体类 **/ 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='" + name + '\ '' + ", age=" + age + '}' ; } } |
输出结果:
[{"name":"zhangsan","age":18},{"name":"lisi","age":23}]
[Body{name='zhangsan', age=18}, Body{name='lisi', age=23}]
2:List转JSONArray
1 2 | List<T> list = new ArrayList<T>(); JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list)); |