日常开发中免不了和json格式的字符串数组,list,json,map打交道,因此这篇文章的着重点就是这四者的相互转换
1、json格式的字符串数组转list
String json = "['北京','天津','杭州']";//"[\"北京\",\"天津\",\"杭州\"]";String[] pathArr = (json.substring(1, json.length() - 1)).split(",");//string数组// 使用Arrays.asList 转换List<String> pathList = Arrays.asList(pathArr);for (String s : pathList) {System.out.println(s);}//使用collectionsList list=new ArrayList();Collections.addAll(list,pathArr);for (Object o : list) {System.out.println(o);}
2、list转json格式数组
List<String> list1=new ArrayList<String>();list1.add("a");list1.add("b");list1.add("vc");JSONArray jsonArray = JSONArray.fromObject(list1);String string=jsonArray.toString();//stringString[] sd = (string.substring(1, string.length() - 1)).split(",");//string数组System.out.println(sd instanceof String[]);for (String s : sd) {System.out.println(s);}
3、list转JSONArray
JSONArray jsonArray1=JSONArray.fromObject(list1);
4、JSONArray转list
List<String> list1=new ArrayList<String>();list1.add("a");list1.add("b");list1.add("vc");JSONArray jsonArray1=JSONArray.fromObject(list1);List<String> list=JSONArray.toList(jsonArray1);for (String s : list) {System.out.println(s);}
5、Java对象、list、map转json字符串
JSONObject.toJSONString(user);JSONObject.toJSONString(list);JSONObject.toJSONString(map);
6、json字符串转java对象、list、map
Employee employee=new Employee();employee.setA("a");employee.setB("bb");employee.setC("cc");String s= JSONObject.toJSONString(employee);//Java对象转json字符串System.out.println(s);employee=JSONObject.parseObject(s,Employee.class);//json字符串转java对象System.out.println(employee.toString());public static String jsonmap = "{\"001\": {\"name\":\"xiaohong\",\"password\":\"654321\"},\"002\":[{\"$ref\":\"$.001\"},{\"name\":\"xixi\",\"password\":\"789\"}]}";public static String jsonuser = "{\"name\":\"xiaohong\",\"password\":\"654321\"}";public static String jsonlist = "[{\"name\":\"xiaohong\",\"password\":\"654321\"},{\"name\":\"xixi\",\"password\":\"789\"}]"; List list1 = JSONObject.parseObject(jsonlist, List.class);//jsonlist转listMap map1 = JSONObject.parseObject(jsonmap, Map.class);//jsonmap转map