转换成Json格式的数据并且可以看转换后的结果

【转换成Json格式的数据并且可以看转换后的结果】需要的jar包:json-lib-2.4-jdk15.jar

package com.xxx.xxx.json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonMain { public static void main(String[] args) {/** * 对于【数组】和【list集合】使用JSONArray.fromObject("#########"); * * 对于【map集合】 和 【对象 】使用JSONObject.fromObject("#########"); */// java数组转json int数组 int[] arr = { 4, 8, 6, 4, 8, 7 }; JSONArray jsonArr = JSONArray.fromObject(arr); System.out.println(jsonArr); //[4,8,6,4,8,7]// java数组转json String数组 String[] arrStr = { "qq", "ww", "ee", "rr" }; JSONArray jsonArrStr = JSONArray.fromObject(arrStr); System.out.println(jsonArrStr); /["qq","ww","ee","rr"]// list集合转json list集合 ArrayList list = new ArrayList<>(); list.add("aa"); list.add("bb"); list.add("cc"); JSONArray jsonList = JSONArray.fromObject(list); System.out.println(jsonList); ///["aa","bb","cc"]// list 集合 ArrayList userList = new ArrayList<>(); userList.add(new User("站三", 18)); userList.add(new User("李四", 34)); userList.add(new User("王五", 24)); JSONArray listArrList = JSONArray.fromObject(userList); System.out.println(listArrList); //[{"age":18,"name":"站三"},{"age":34,"name":"李四"},{"age":24,"name":"王五"}] // // map转json HashMap map = new HashMap<>(); map.put("aa", "a11"); map.put("bb", "b11"); map.put("cc", "c11"); JSONObject jsonMap = JSONObject.fromObject(map); System.out.println(jsonMap); /{"aa":"a11","bb":"b11","cc":"c11"}// map转json HashMap map1 = new HashMap<>(); map1.put("aa", 111); map1.put("bb", 222); map1.put("cc", 333); JSONObject jsonMap1 = JSONObject.fromObject(map1); System.out.println(jsonMap1); {"aa":111,"bb":222,"cc":333}// 对象转json User User user1 = new User("站三", 18); JSONObject user1Json = JSONObject.fromObject(user1); System.out.println(user1Json); ///{"age":18,"name":"站三"}User user2 = new User("李四", 18); JSONObject user2Json = JSONObject.fromObject(user2); System.out.println(user2Json); //{"age":18,"name":"李四"} }}


    推荐阅读