本文介绍Java的Bean实体对象和Map互相转换的几种方法


目录
  • 方式一:Hutool工具类
  • 方式二:Jackson库
  • 参考


测试用到的实体类

@Data
class Person {
    private String name;
    private Integer age;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

方式一:Hutool工具类

依赖

<!-- hutool -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.4.6</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

引入工具类

import cn.hutool.core.bean.BeanUtil;
  • 1.

对象转换为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}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

方式二:Jackson库

依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.4</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
import com.fasterxml.jackson.databind.ObjectMapper;
  • 1.

对象转换为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}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

参考

1、java中对象和Map互相转换的几种方式