1.序列化类信息
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
注:这里使用了lomok工具包,不用再次封装成员信息,有构造器和getter()和setter()方法
2.创建专门的类进行转换
一个是List转String,一个是String转List
public class JaksonExecutor {
private ObjectMapper mapper=new ObjectMapper();
//序列化类对象
public String UserToJson (List<User> list){
String res="";
try {
res= mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return res;
}
//反序列化
public List<User> JsonToUser(String strs) throws IOException {
List<User> list= mapper.readValue(strs,new TypeReference<List<User>>(){});
return list;
}
}
如果只是单一对象的话,用下面方法:
User user=mapper.readValue(strs,User.class);
3.调用方法
@RequestMapping("/thymeleaf")
public void showInfo() throws IOException {
List<User> list=new ArrayList<>();
User user=new User(1,"likui","123");
User user2=new User(2,"admin","123");
list.add(user);
list.add(user2);
String str=new JaksonExecutor().UserToJson(list);
System.out.println(str);
list=new JaksonExecutor().JsonToUser(str);
System.out.println(list);
}