java的String转换list

最近面试的时候有一些心得总结是关于String转换list的

代码如下:

String sL = "["

  + "{\"id\":\"1\",\"name\":\"张三\"},"

  + "{\"id\":\"2\",\"name\":\"李四\"},"

  + "{\"id\":\"3\",\"name\":\"王五\"},"

  + "{\"id\":\"4\",\"name\":\"李雷\"}"

  + "]";

String sS = "[{\"stuId\":\"1\", \"subjectId\":\"1\", \"subjectName\":\"英语\", \"score\":\"90\"},"

  + "{\"stuId\":\"1\", \"subjectId\":\"2\", \"subjectName\":\"数学\", \"score\":\"80\"},"

  + "{\"stuId\":\"1\", \"subjectId\":\"3\", \"subjectName\":\"语文\", \"score\":\"70\"},"

  + "{\"stuId\":\"2\", \"subjectId\":\"1\", \"subjectName\":\"英语\", \"score\":\"85\"},"

  + "{\"stuId\":\"2\", \"subjectId\":\"2\", \"subjectName\":\"数学\", \"score\":\"75\"},"

  + "{\"stuId\":\"2\", \"subjectId\":\"3\", \"subjectName\":\"语文\", \"score\":\"90\"},{\"stuId\":\"3\", \"subjectId\":\"3\", \"subjectName\":\"语文\", \"score\":\"60\"}]";

List<Map<String,Object>>list = new ArrayList<Map<String,Object>>();

List<Map<String,Object>>list1 = new ArrayList<Map<String,Object>>();

sL = sL.replaceAll("[\\[\\]]", "");//去除方括号

String[] splitArray = sL.split("},");//去除大括号

sS = sS.replaceAll("[\\[\\]]", "");//去除方括号

String[] splitArray1 = sS.split("},");//去除大括号

for(int i=0; i<splitArray.length;i++) {

 if(i==splitArray.length-1) {

  splitArray[i] = splitArray[i].substring(1, splitArray[i].length()-1);

 }else {

  splitArray[i]=splitArray[i].substring(1, splitArray[i].length());

 }

 

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

 

 

 String[] mapArray = splitArray[i].split(",");

 for(int j=0 ;j<mapArray.length ;j++) {

  String str = mapArray[j].replaceAll("\"", "");

  String[] keyValue = str.split(": ");

  //防止value为空

 

  if(keyValue.length==2)

   map.put(keyValue[0], keyValue[1]);

  else

   map.put(keyValue[0], "");

   }

 list.add(map);

 }

for(int i=0; i<splitArray1.length;i++) {

 if(i==splitArray1.length-1) {

  splitArray1[i] = splitArray1[i].substring(1, splitArray1[i].length()-1);

 }else {

  splitArray1[i]=splitArray1[i].substring(1, splitArray1[i].length());

 }

 

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

 

 String[] mapArray1 = splitArray1[i].split(",");

 for(int j=0 ;j<mapArray1.length ;j++) {

  String str = mapArray1[j].replaceAll("\"", "");

 

  String[] keyValue = str.split(":");

 

  if(keyValue.length==2)

   map1.put(keyValue[0], keyValue[1]);

  else

   map1.put(keyValue[0], "");

   }

 list1.add(map1);

 }

这是两个string的转换list但是没有把两个list合并键和值的理解自己看一看

string先转换成map再转换成list

这个是大厂的邮箱面试题,大家可以做个参考学习


上一篇:2021年12月1号 linux系统优化


下一篇:2021年11月30号 Linux基础操作文件+命令解析(面试重点)