Java中List和fastjson的JSONArray相互转换代码示例,
分享于 点击 2750 次 点评:139
Java中List和fastjson的JSONArray相互转换代码示例,
目录
- List和JSONArray相互转换
- List转JSONArray
- JSONArray转List
- 总结
List和JSONArray相互转换
List转JSONArray
复制完直接运行,代码如下:
System.out.println("List转JSONArray"); List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); System.out.println("\n原始list: " + list); // 方式1:使用JSONArray构造方法 JSONArray jsonArray1 = new JSONArray(Collections.singletonList(list)); System.out.println("方式1:" + jsonArray1); // 方式2:将List转换为JSON字符串,两种都可以 JSONArray jsonArray2 = JSONArray.parseArray(JSONArray.toJSONString(list)); //JSONArray jsonArray2 = JSONArray.parseArray(JSON.toJSONString(list)); System.out.println("方式2:" + jsonArray2); // 方式3:将List转换为JSON字符串,再强转 JSONArray jsonArray3 = (JSONArray) JSONObject.toJSON(list); System.out.println("方式3:" + jsonArray3);
JSONArray转List
System.out.println("JSONArray转List"); JSONArray array = new JSONArray(); array.add("a"); array.add("b"); array.add("c"); System.out.println("\n原始 JSONArray: " + array); // 两种都能用 List<String> strList = JSONArray.parseArray(array.toJSONString(), String.class); // List<String> strList = JSONObject.parseArray(array.toJSONString(), String.class); System.out.println("JSONArray.parseArray: " + strList);
总结
到此这篇关于Java中List和fastjson的JSONArray相互转换的文章就介绍到这了,更多相关List和fastjson的JSONArray相互转换内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!
您可能感兴趣的文章:- Java使用fastjson对String、JSONObject、JSONArray相互转换
- java中JSONArray互相转换List的实现
- 详解Java中String JSONObject JSONArray List<实体类>转换
- ArrayList和JSONArray边遍历边删除到底该如何做
用户点评