Java對(duì)象和Map之間相互轉(zhuǎn)換的五種方法
引言
在Java開(kāi)發(fā)中,經(jīng)常需要將Java對(duì)象轉(zhuǎn)換成Map,或者反過(guò)來(lái)將Map轉(zhuǎn)換成Java對(duì)象。這種轉(zhuǎn)換在很多場(chǎng)景下都非常有用,比如在序列化和反序列化過(guò)程中、在數(shù)據(jù)傳輸和持久化時(shí)、或者在進(jìn)行對(duì)象屬性的批量操作時(shí)。
本文將介紹幾種不同的方法來(lái)實(shí)現(xiàn)Java對(duì)象和Map之間的相互轉(zhuǎn)換,選擇哪種方法取決于項(xiàng)目的具體需求和個(gè)人偏好。
一、使用Spring Framework的ReflectionUtils
1.1、Bean轉(zhuǎn)為Map
@Test
public void bean2Map(){
Person person=new Person();
person.setName("tiger");
person.setAge(18);
person.setAddress("中國(guó)");
person.setCity("深圳");
System.out.println(person);
System.out.println(bean2Map(person));
System.out.println(bean2Map2(person));
}
public static Map<String, Object> bean2Map(Object object) {
Map<String, Object> map = new HashMap<>();
ReflectionUtils.doWithFields(object.getClass(), field -> {
field.setAccessible(true);
Object value = ReflectionUtils.getField(field, object);
if (value != null) {
map.put(field.getName(), value);
}
});
return map;
}
public static Map<String, Object> bean2Map2(Object object) {
Map<String, Object> map = new HashMap<>();
Class<?> clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(object);
if (value != null) {
map.put(field.getName(), value);
}
} catch (IllegalAccessException e) {
throw new RuntimeException("Error accessing field: " + field.getName(), e);
}
}
return map;
}
結(jié)果輸出:

1.2、Map轉(zhuǎn)為Bean
@Test
public void map2bean() throws IllegalAccessException, InstantiationException {
Map<String, Object> map = new HashMap();
map.put("name", "tigerhhzz");
map.put("age", 18);
map.put("address","中國(guó)");
map.put("city", "北京");
System.out.println(map);
System.out.println(map2Bean(map, Person.class));
System.out.println(map2Bean2(map, Person.class));
}
public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz) throws IllegalAccessException, InstantiationException {
T instance = clazz.newInstance();
ReflectionUtils.doWithFields(clazz, field -> {
field.setAccessible(true);
if (map.containsKey(field.getName())) {
ReflectionUtils.setField(field, instance, map.get(field.getName()));
}
});
return instance;
}
public static <T> T map2Bean2(Map<String, Object> map, Class<T> clazz) throws IllegalAccessException, InstantiationException {
T instance = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (map.containsKey(field.getName())) {
field.set(instance, map.get(field.getName()));
}
}
return instance;
}
結(jié)果輸出:

二、使用Hutool工具
2.1、引入hutool依賴
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.5.9</version> </dependency>
2.2、Bean轉(zhuǎn)為Map
@Test
public void bean2Map(){
Person person=new Person();
person.setName("tiger");
person.setAge(18);
person.setAddress("中國(guó)");
person.setCity("深圳");
Map<String, Object> map = BeanUtil.beanToMap(person);
System.out.println(person);
System.out.println(bean2Map(person));
System.out.println(bean2Map2(person));
System.out.println(map);
}
結(jié)果輸出:

2.3、Map轉(zhuǎn)為Bean
@Test
public void map2bean() throws IllegalAccessException, InstantiationException {
Map<String, Object> map = new HashMap();
map.put("name", "tigerhhzz");
map.put("age", 18);
map.put("address","中國(guó)");
map.put("city", "北京");
Person person = BeanUtil.toBean(map, Person.class);
System.out.println(map);
System.out.println(map2Bean(map, Person.class));
System.out.println(map2Bean2(map, Person.class));
System.out.println(person);
}
結(jié)果輸出:

三、使用Jackson工具
3.1、Bean轉(zhuǎn)為Map
@Test
public void bean2Map(){
Person person=new Person();
person.setName("tiger");
person.setAge(18);
person.setAddress("中國(guó)");
person.setCity("深圳");
Map<String, Object> map = BeanUtil.beanToMap(person);
System.out.println(person);
System.out.println(bean2Map(person));
System.out.println(bean2Map2(person));
System.out.println(map);
System.out.println(bean2MapByjackson(person));
}
轉(zhuǎn)換方法:
public static Map<String, Object> bean2MapByjackson(Object object) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(object, new TypeReference<Map<String, Object>>() {
});
}
結(jié)果輸出:

3.2、Map轉(zhuǎn)為Bean
@Test
public void map2bean() throws IllegalAccessException, InstantiationException {
Map<String, Object> map = new HashMap();
map.put("name", "tigerhhzz");
map.put("age", 18);
map.put("address","中國(guó)");
map.put("city", "北京");
Person person = BeanUtil.toBean(map, Person.class);
System.out.println(map);
System.out.println(map2BeanByReflectionUtils(map, Person.class));
System.out.println(map2Bean2ByReflectionUtils(map, Person.class));
System.out.println(person);
System.out.println(map2BeanByjackson(map, Person.class));
}
轉(zhuǎn)換方法:
public static <T> T map2BeanByjackson(Map<String, Object> map, Class<T> clazz){
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(map, clazz);
}
結(jié)果輸出:

四、使用Apache Commons Lang的BeanUtils
4.1、引入依賴
<!-- commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.4</version> </dependency>
4.2、Bean轉(zhuǎn)為Map
轉(zhuǎn)換方法:
public static Map<String, String> bean2MapBycommonslang3(Object object) {
try {
return BeanUtils.describe(object);
} catch (Exception e) {
throw new RuntimeException("Error converting object to map: " + e.getMessage(), e);
}
}
@Test
public void bean2Map(){
Person person=new Person();
person.setName("tiger");
person.setAge(18);
person.setAddress("中國(guó)");
person.setCity("深圳");
Map<String, Object> map = BeanUtil.beanToMap(person);
System.out.println(person);
System.out.println(bean2Map(person));
System.out.println(bean2Map2(person));
System.out.println(map);
System.out.println(bean2MapByjackson(person));
System.out.println(bean2MapBycommonslang3(person));
}
結(jié)果輸出:

4.3、Map轉(zhuǎn)為Bean
轉(zhuǎn)換方法:
public static <T> T map2BeanBycommonslang3(Map<String, ?> map, Class<T> clazz) {
try {
T instance = clazz.newInstance();
BeanUtils.populate(instance, map);
return instance;
} catch (Exception e) {
throw new RuntimeException("Error converting map to object: " + e.getMessage(), e);
}
}
@Test
public void map2bean() throws IllegalAccessException, InstantiationException {
Map<String, Object> map = new HashMap();
map.put("name", "tigerhhzz");
map.put("age", 18);
map.put("address","中國(guó)");
map.put("city", "北京");
Person person = BeanUtil.toBean(map, Person.class);
System.out.println(map);
System.out.println(map2BeanByReflectionUtils(map, Person.class));
System.out.println(map2Bean2ByReflectionUtils(map, Person.class));
System.out.println(person);
System.out.println(map2BeanByjackson(map, Person.class));
System.out.println(map2BeanBycommonslang3(map, Person.class));
}
結(jié)果輸出:

五、使用fastjson工具
5.1、 引入fastjson依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
5.2、 Bean轉(zhuǎn)為Map
@Test
public void bean2Map(){
Person person=new Person();
person.setName("tiger");
person.setAge(18);
person.setAddress("中國(guó)");
person.setCity("深圳");
Map<String, Object> map = BeanUtil.beanToMap(person);
System.out.println(person);
System.out.println(bean2Map(person));
System.out.println(bean2Map2(person));
System.out.println(map);
System.out.println(bean2MapByjackson(person));
System.out.println(bean2MapBycommonslang3(person));
System.out.println(JSONObject.parseObject(JSONObject.toJSONString(person)));
}
結(jié)果輸出:

5.3、 Map轉(zhuǎn)為Bean
@Test
public void map2bean() throws IllegalAccessException, InstantiationException {
Map<String, Object> map = new HashMap();
map.put("name", "tigerhhzz");
map.put("age", 18);
map.put("address","中國(guó)");
map.put("city", "北京");
Person person = BeanUtil.toBean(map, Person.class);
System.out.println(map);
System.out.println(map2BeanByReflectionUtils(map, Person.class));
System.out.println(map2Bean2ByReflectionUtils(map, Person.class));
System.out.println(person);
System.out.println(map2BeanByjackson(map, Person.class));
System.out.println(map2BeanBycommonslang3(map, Person.class));
System.out.println(JSONObject.parseObject(JSONObject.toJSONString(map), Person.class));
}
結(jié)果輸出:

以上就是Java對(duì)象和Map之間相互轉(zhuǎn)換的五種方法的詳細(xì)內(nèi)容,更多關(guān)于Java對(duì)象和Map互轉(zhuǎn)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java日期毫秒值和常見(jiàn)日期時(shí)間格式相互轉(zhuǎn)換方法
這篇文章主要給大家介紹了關(guān)于Java日期毫秒值和常見(jiàn)日期時(shí)間格式相互轉(zhuǎn)換的相關(guān)資料,在Java的日常開(kāi)發(fā)中,會(huì)隨時(shí)遇到需要對(duì)時(shí)間處理的情況,文中給出了詳細(xì)的示例代碼,需要的朋友可以參考下2023-07-07
關(guān)于springcloud報(bào)錯(cuò)報(bào)UnsatisfiedDependencyException的問(wèn)題
這篇文章主要介紹了關(guān)于springcloud報(bào)錯(cuò)報(bào)UnsatisfiedDependencyException的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
Spring Boot 整合 Mockito提升Java單元測(cè)試的高效實(shí)踐案例
Mockito與Spring Boot的整合為Java開(kāi)發(fā)者提供了一套完整的解決方案,使得單元測(cè)試更為精準(zhǔn)、高效,從而確保了代碼質(zhì)量、降低了維護(hù)成本,并促進(jìn)了項(xiàng)目的持續(xù)集成與交付,感興趣的朋友跟隨小編一起看看吧2024-04-04
Java中的HashMap為什么會(huì)產(chǎn)生死循環(huán)
這篇文章主要介紹了Java中的HashMap為什么會(huì)產(chǎn)生死循環(huán),HashMap?死循環(huán)是一個(gè)比較常見(jiàn)、比較經(jīng)典的問(wèn)題,下面文章我們就來(lái)徹底理解死循環(huán)的原因。需要的小伙伴可以參考一下2022-05-05
SSH框架網(wǎng)上商城項(xiàng)目第3戰(zhàn)之使用EasyUI搭建后臺(tái)頁(yè)面框架
SSH框架網(wǎng)上商城項(xiàng)目第3戰(zhàn)之使用EasyUI搭建后臺(tái)頁(yè)面框架,討論兩種搭建方式:基于frameset和基于easyUI,感興趣的小伙伴們可以參考一下2016-05-05
基于java ssm springboot實(shí)現(xiàn)選課推薦交流平臺(tái)系統(tǒng)
這篇文章主要介紹了選課推薦交流平臺(tái)系統(tǒng)是基于java ssm springboot來(lái)的實(shí)現(xiàn)的,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
Springboot啟動(dòng)不檢查JPA的數(shù)據(jù)源配置方式
這篇文章主要介紹了Springboot啟動(dòng)不檢查JPA的數(shù)據(jù)源配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
spring boot 自定義規(guī)則訪問(wèn)獲取內(nèi)部或者外部靜態(tài)資源圖片的方法
這篇文章主要介紹了spring boot 自定義規(guī)則訪問(wèn)獲取內(nèi)部或者外部靜態(tài)資源圖片的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01

