json字符串转换为Array or List

来源:互联网 发布:淘宝有哪些冷门的类目 编辑:程序博客网 时间:2024/06/08 00:16
  1. 将json字符串转成Java的Array数组   
  2. private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+   
  3. "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";   
  4.   
  5. @Test  
  6. public void readJSON2Array() {   
  7. try {   
  8.   
  9. json = "[" + json + "]";   
  10. jsonArray = JSONArray.fromObject(json);   
  11.   
  12. Object[] os = jsonArray.toArray();   
  13. System.out.println(os.length);   
  14.   
  15.   
  16. Student[] stus = (Student[]) JSONArray.toArray(jsonArray, Student.class);   
  17. System.out.println(stus.length);   
  18. System.out.println(stus[0]);   
  19. catch (Exception e) {   
  20. e.printStackTrace();   
  21. }   
  22. }   
  23.   
  24.   运行的结果如下:   
  25. ==============JSON Arry String >>> Java Array ==================   
  26. #%%%{"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}   
  27. 1  
  28. {"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}   
  29. {"address":"chian","birthday":{"birthday":"2010-11-22"},"email":"email@123.com","id":22,"name":"tom"}   
  30. 1  
  31.   
  32.   
  33.   将JSON字符串转成Java的List集合   
  34. private String json = "{\"address\":\"chian\",\"birthday\":{\"birthday\":\"2010-11-22\"},"+   
  35. "\"email\":\"email@123.com\",\"id\":22,\"name\":\"tom\"}";   
  36.   
  37.   
  38. public void readJSON2List() {   
  39. try {   
  40.   
  41. json = "[" + json + "]";   
  42. jsonArray = JSONArray.fromObject(json);   
  43. List<Student> list = JSONArray.toList(jsonArray, Student.class);   
  44. System.out.println(list.size());   
  45. System.out.println(list.get(0));   
  46.   
  47. list = JSONArray.toList(jsonArray);   
  48. System.out.println(list.size());   
  49. System.out.println(list.get(0));   
  50. catch (Exception e) {   
  51. e.printStackTrace();   
  52. }   
  53. }   
  54.   
  55.   运行后结果如下:   
  56. ==============JSON Arry String >>> Java List ==================   
  57. 1  
  58. tom#22#chian#2010-11-22#email@123.com   
  59. 1  
  60. net.sf.ezmorph.bean.MorphDynaBean@141b571[   
  61. {id=22, birthday=net.sf.ezmorph.bean.MorphDynaBean@b23210[   
  62. {birthday=2010-11-22}   
  63. ], address=chian, email=email@123.com, name=tom}   
  64. ]  
原创粉丝点击