1. Jackson
坐标
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</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 对集合泛型的反序列化
private ObjectMapper mapper =new ObjectMapper();
user user = new user("张三",23);
//对象转json
String json = mapper.writeValueAsString(user);
System.out.println(json);
//json转对象
user user1 = mapper.readValue(json, user.class);
System.out.println(user1);
//map转json
HashMap<String,String> map =new HashMap<>();
map.put("姓名","张三");
map.put("性别","男");
String s = mapper.writeValueAsString(map);
System.out.println(s);
//json转map
HashMap<String,String> hashMap = mapper.readValue(s, HashMap.class);
System.out.println(hashMap);
//map<String,user> 转json
HashMap<String,user> map2 =new HashMap<>();
map2.put("一班",new user("张三",23));
map2.put("二班",new user("李四",23));
String s1 = mapper.writeValueAsString(map2);
System.out.println(s1);
//json转 map<String,user>
HashMap<String,user> map3=mapper.readValue(s1,new TypeReference<HashMap<String,user>>(){});
System.out.println(map3);
//List<String> 换json
ArrayList<String> list=new ArrayList<>();
list.add("张三");
list.add("李四");
String s2 = mapper.writeValueAsString(list);
System.out.println(s2);
//List<String> 转json
ArrayList arrayList = mapper.readValue(s2, ArrayList.class);
System.out.println(arrayList);
//List<user> 换json
ArrayList<user> list2=new ArrayList<>();
list2.add(new user("张三",23));
list2.add(new user("王五",22));
String s3 = mapper.writeValueAsString(list2);
System.out.println(s3);
//List<user> 转json
ArrayList<user> arrayList2 = mapper.readValue(s3, new TypeReference<ArrayList<user>>(){});
System.out.println(arrayList2);