java中将数组、对象、Map、List转换成JSON数据
如果要将数组、对象、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
1 // 将数组转换为JSON: 2 3 String[] arr = {"asd","dfgd","asd","234"}; 4 5 JSONArray jsonarray = JSONArray.fromObject(arr); 6 7 System.out.println(jsonarray); 8 9 10 11 // 对象转换成JSON: 12 13 UserInfo user = new UserInfo(1001,"张三"); 14 15 JSONArray jsonArray = JSONArray.fromObject(user); 16 17 System.out.println( jsonArray ); 18 19 20 // 把Map转换成json, 要使用jsonObject对象: 21 22 Map<String, Object> map = new HashMap<String, Object>(); 23 24 map.put("userId", 1001); 25 26 map.put("userName", "张三"); 27 28 map.put("userSex", "男"); 29 30 JSONObject jsonObject = JSONObject.fromObject(map); 31 32 System.out.println(jsonObject); 33 34 35 // 把List转换成JSON数据: 36 37 List<UserInfo> list = new ArrayList<UserInfo>(); 38 39 UserInfo user = new UserInfo(1001, "张三"); 40 41 list.add(user); 42 43 list.add(user); 44 45 list.add(user); 46 47 JSONArray jsonArray = JSONArray.fromObject(list); 48 49 System.out.println(jsonArray);
毕竟人生那么长,如果不喜欢做开发,就别和bug较劲了。