1. package com.wing.mall.cloud.base.test.json;
  2. import com.alibaba.druid.support.json.JSONUtils;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONArray;
  5. import lombok.Data;
  6. import java.util.*;
  7. @Data
  8. public class Person {
  9. //@JSONField(name = "AGE")
  10. private int age;
  11. //@JSONField(name = "FULL NAME")
  12. private String fullName;
  13. //@JSONField(name = "DATE OF BIRTH")
  14. private Date dateOfBirth;
  15. public Person(int age, String fullName, Date dateOfBirth) {
  16. super();
  17. this.age = age;
  18. this.fullName= fullName;
  19. this.dateOfBirth = dateOfBirth;
  20. }
  21. public static void main(String[] args) {
  22. Person zhangsan = new Person(18, "zhangsan", new Date());
  23. //1:对象转JSON字符串
  24. String string = JSON.toJSONString(zhangsan);
  25. System.out.println(string);
  26. /**输出:
  27. * {"age":18,"dateOfBirth":1591749219656,"fullName":"zhangsan"}
  28. */
  29. //-------------------------------------
  30. //2:JSON字符串转对象
  31. Person person = JSON.parseObject(string,Person.class);
  32. System.out.println(person);
  33. /**
  34. * 输出:
  35. * Person(age=18, fullName=zhangsan, dateOfBirth=Wed Jun 10 08:47:12 GMT+08:00 2020)
  36. */
  37. //--------------------------------------
  38. //3:list对象转JSON字符串
  39. List<Person> listOfPersons = new ArrayList<Person>();
  40. listOfPersons.add(new Person(19, "lisi", new Date()));
  41. listOfPersons.add(new Person(20, "wanger", new Date()));
  42. String string1 = JSON.toJSONString(listOfPersons);
  43. System.out.println(string1);
  44. /**
  45. * 输出:
  46. * [{"age":19,"dateOfBirth":1591749437754,"fullName":"lisi"},{"age":20,"dateOfBirth":1591749437754,"fullName":"wanger"}]
  47. */
  48. //----------------------------------------
  49. //4: list的字符串转List集合。
  50. List<Person> ts = (List<Person>) JSONArray.parseArray(string1, Person.class);
  51. ts.forEach(person1 -> {
  52. System.out.println(person1);
  53. });
  54. /**
  55. * 输出:
  56. * Person(age=19, fullName=lisi, dateOfBirth=Wed Jun 10 09:19:14 GMT+08:00 2020)
  57. * Person(age=20, fullName=wanger, dateOfBirth=Wed Jun 10 09:19:14 GMT+08:00 2020)
  58. */
  59. //-------------------------------------------------
  60. //5:Map转JSON字符串
  61. Map<String, Object> map = new HashMap<>();
  62. map.put("a", "aaa");
  63. map.put("b", "bbb");
  64. map.put("c", 1);
  65. String string2 = JSONUtils.toJSONString(map);
  66. System.out.println(string2);
  67. /**
  68. * 输出:
  69. * {"a":"aaa","b":"bbb","c":1}
  70. */
  71. //---------------
  72. //6:JSON字符串转Map
  73. Map<String, Object> maps = (Map<String, Object>) JSON.parse(string2);
  74. maps.forEach((k,v)->{
  75. System.out.println("k:" + k + " " + "v:" + v);
  76. });
  77. /**
  78. * 输出:
  79. * k:a v:aaa
  80. * k:b v:bbb
  81. * k:c v:1
  82. */
  83. }
  84. }

 

版权声明:本文为bulrush原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/bulrush/p/13083072.html