实体类和 Map互相转换
使用 JSON.parseObject(JSON.toJSONString(map), 类型.class)
// 实体类转换为Map
Map map = JSON.parseObject(JSON.toJSONString(student), Map.class);
// Map转实体类
Student student = JSON.parseObject(JSON.toJSONString(map), User.class);
例子:
实体类代码:
public class Student {
private String name;
private Integer age;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
测试类代码:
Student student = new Student();
student.setName("张三");
student.setAge(10);
student.setGender("男");
// 实体类转换为Map
Map map = JSON.parseObject(JSON.toJSONString(student), Map.class);
map.forEach((key,value)->{
System.out.println("key:" + key + ", value:" + value);
});
// Map转实体类
Student student1 = JSON.parseObject(JSON.toJSONString(map), Student.class);
System.out.println("姓名"+student1.getName());
System.out.println("年龄"+student1.getAge());
System.out.println("性别"+student1.getGender());
参考:实体类转 Map_实体类转map_Rock(洛克)的博客-CSDN博客