java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > List和fastjson的JSONArray相互转换

Java中List和fastjson的JSONArray相互转换代码示例

作者:rgb0f0

这篇文章主要介绍了如何在Java中将List和JSONArray相互转换,展示了如何将List转换为JSONArray,并且可以直接运行这段代码,需要的朋友可以参考下

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相互转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文