这篇文章主要讲解了“java中JSONArray互相转换List怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“java中JSONArray互相转换List怎么实现”吧!
1:JSONArray转List
JSONArray字符串 转 List
//初始化JSONArrayJSONArray 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
//初始化JSONArrayJSONArray jsonArray = JSONArray.parseArray("[{\"name\":\"zhangsan\",\"age\":18},{\"name\":\"lisi\",\"age\":23}]");//打印jsonArraySystem.out.println(jsonArray.toJSONString());//转ListList<Body> list = JSONArray.parseArray(jsonArray.toJSONString(), Body.class);//打印List<Body>System.out.println(list.toString());
Body.class代码:
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
List<T> list = new ArrayList<T>();JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
感谢各位的阅读,以上就是“java中JSONArray互相转换List怎么实现”的内容了,经过本文的学习后,相信大家对java中JSONArray互相转换List怎么实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!