java中将数组、对象、Map、List转换成JSON数据

时间:2021-08-12 07:19:23

如果要将数组、对象、Map、List转换成JSON数据,那我们需要一些jar包:

json-lib-2.4-jdk15.jar

ezmorph-1.0.6.jar

commons-logging.jar

commons-lang.jar

commons-collections.jar

commons-beanutils.jar

maven依赖
https://blog.csdn.net/baidu_35468322/article/details/81207337

 // 将数组转换为JSON:

 String[] arr = {"asd","dfgd","asd","234"};

 JSONArray jsonarray = JSONArray.fromObject(arr);

 System.out.println(jsonarray);

 // 对象转换成JSON:

 UserInfo user = new UserInfo(1001,"张三");

 JSONArray jsonArray = JSONArray.fromObject(user);  

 System.out.println( jsonArray );  

 // 把Map转换成json, 要使用jsonObject对象:

 Map<String, Object> map = new HashMap<String, Object>();

 map.put("userId", 1001);

 map.put("userName", "张三");

 map.put("userSex", "男");

 JSONObject jsonObject = JSONObject.fromObject(map);

 System.out.println(jsonObject);

 // 把List转换成JSON数据:

 List<UserInfo> list = new ArrayList<UserInfo>();

 UserInfo user = new UserInfo(1001, "张三");

 list.add(user);

 list.add(user);

 list.add(user);

 JSONArray jsonArray = JSONArray.fromObject(list);

 System.out.println(jsonArray);