1. Jackson

坐标

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>2.9.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.fasterxml.jackson.core</groupId>
  8. <artifactId>jackson-core</artifactId>
  9. <version>2.9.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.fasterxml.jackson.core</groupId>
  13. <artifactId>jackson-annotations</artifactId>
  14. <version>2.9.0</version>
  15. </dependency>

Jackson是把JSON 转为java对象或者集合的一个工具类

SpringMVC 转换默认使用 Jackson

  • ObjectMapper 实现JSON字符串和对象之间的转换

    • writeValueAsString(object obj) 将java对象转为json字符串
    • <T> T readValue(String json,class<T> valueTType) 将json字符串转为java对象
    • <T> T readValue(String json,TypeReferncevalueTType) 将json字符串转为java对象
  • TypeReference 对集合泛型的反序列化
  1. private ObjectMapper mapper =new ObjectMapper();
  2. user user = new user("张三",23);
  3. //对象转json
  4. String json = mapper.writeValueAsString(user);
  5. System.out.println(json);
  6. //json转对象
  7. user user1 = mapper.readValue(json, user.class);
  8. System.out.println(user1);
  9. //map转json
  10. HashMap<String,String> map =new HashMap<>();
  11. map.put("姓名","张三");
  12. map.put("性别","男");
  13. String s = mapper.writeValueAsString(map);
  14. System.out.println(s);
  15. //json转map
  16. HashMap<String,String> hashMap = mapper.readValue(s, HashMap.class);
  17. System.out.println(hashMap);
  18. //map<String,user> 转json
  19. HashMap<String,user> map2 =new HashMap<>();
  20. map2.put("一班",new user("张三",23));
  21. map2.put("二班",new user("李四",23));
  22. String s1 = mapper.writeValueAsString(map2);
  23. System.out.println(s1);
  24. //json转 map<String,user>
  25. HashMap<String,user> map3=mapper.readValue(s1,new TypeReference<HashMap<String,user>>(){});
  26. System.out.println(map3);
  27. //List<String> 换json
  28. ArrayList<String> list=new ArrayList<>();
  29. list.add("张三");
  30. list.add("李四");
  31. String s2 = mapper.writeValueAsString(list);
  32. System.out.println(s2);
  33. //List<String> 转json
  34. ArrayList arrayList = mapper.readValue(s2, ArrayList.class);
  35. System.out.println(arrayList);
  36. //List<user> 换json
  37. ArrayList<user> list2=new ArrayList<>();
  38. list2.add(new user("张三",23));
  39. list2.add(new user("王五",22));
  40. String s3 = mapper.writeValueAsString(list2);
  41. System.out.println(s3);
  42. //List<user> 转json
  43. ArrayList<user> arrayList2 = mapper.readValue(s3, new TypeReference<ArrayList<user>>(){});
  44. System.out.println(arrayList2);