阅读量:0
本文介绍Java的Bean实体对象和Map互相转换的几种方法
目录
测试用到的实体类
@Data class Person { private String name; private Integer age; }
方式一:Hutool工具类
依赖
<!-- hutool --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.4.6</version> </dependency>
引入工具类
import cn.hutool.core.bean.BeanUtil;
对象转换为Map
Person person = new Person(); person.setName("Alice"); person.setAge(30); // 对象转换为Map Map<String, Object> map = BeanUtil.beanToMap(person); System.out.println(map); // 输出:{name=Alice, age=30}
Map转换为对象
Map<String, Object> map = new HashMap<>(); map.put("name", "Alice"); map.put("age", 30); // Map转换为对象 Person person = BeanUtil.mapToBean(map, Person.class, true, null); System.out.println(person); // 输出:Person(name=Alice, age=30)
方式二:Jackson库
依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.4</version> </dependency>
import com.fasterxml.jackson.databind.ObjectMapper;
对象转换为Map
Person person = new Person(); person.setName("Alice"); person.setAge(30); ObjectMapper objectMapper = new ObjectMapper(); // 对象转换为Map Map<String, Object> personMap = objectMapper.convertValue(person, Map.class); System.out.println(personMap); // 输出:{name=Alice, age=30}
Map转换为对象
Map<String, Object> map = new HashMap<>(); map.put("name", "Alice"); map.put("age", 30); ObjectMapper objectMapper = new ObjectMapper(); // Map转换为对象 Person person = objectMapper.convertValue(map, Person.class); System.out.println(person); // 输出:Person(name=Alice, age=30)