map与实体类互转DTO、VO互转

互转的前提是属性名相同,如果属性名不同,又要互转,只能自已手写工具类了 1、pom

xml 复制代码
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

2、map转实体类,如果属性里有list会出错

ini 复制代码
Map<String, String> of = ImmutableMap.of("a", "aaaaa", "b", "kluowejbbbb");
Student student = new Student();
BeanUtils.copyProperties(student,of);

DTO转VO

ini 复制代码
StudentVO studentVO = new StudentVO();
studentVO.setAge("sdfsafd");
studentVO.setStudentName("jkljsie");

StudentDTO studentDTO = new StudentDTO();
BeanUtils.copyProperties(studentDTO, studentVO);
System.out.println("studentDTO = " + studentDTO);   // {studentName='jkljsie', age='sdfsafd'}

DTO转map,如果属性里有list会出错

ini 复制代码
StudentVO studentVO = new StudentVO();
studentVO.setAge(12);
studentVO.setStudentName("jkljsie");
Map<String, String> describe = BeanUtils.describe(studentVO); // 如果属性里有list会出错

也可以用fastjson去转换 1、pom

xml 复制代码
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.69</version>
</dependency>

2、先成转json再转成dto

javascript 复制代码
StudentVO studentVO = new StudentVO(12,"aaaaaa");
String s = JSONObject.toJSONString(studentVO);
StudentDTO studentDTO = JSONObject.parseObject(s, StudentDTO.class);

System.out.println("studentDTO = " + studentDTO);  // {studentName='aaaaaa', age='12'}


// 转成map
Map<String,String> hashMap = JSONObject.parseObject(map, HashMap.class);
相关推荐
努力的白熊嗨15 分钟前
多台服务器文件共享存储
服务器·后端
调试人生的显微镜16 分钟前
CSS开发工具推荐与实战经验,让样式开发更高效、更精准
后端
渣哥22 分钟前
多环境配置利器:@Profile 在 Spring 项目中的实战价值
javascript·后端·面试
东百牧码人23 分钟前
还在使用ToList太Low了
后端
缓存征服者28 分钟前
CompletableFuture并行化改造,我将接口响应时间从300ms优化到50ms
后端
什么芋泥香蕉33033 分钟前
比 Manus 还好用?这款国产 AI,让 Python 小白也能玩转编程
前端·后端
xxxcq44 分钟前
Go微服务网关开发(1)--概念介绍
后端
golang学习记1 小时前
Python 3.14 正式发布:七大重磅新特性详解
后端
用户4099322502121 小时前
PostgreSQL里的子查询和CTE居然在性能上“掐架”?到底该站哪边?
后端·ai编程·trae
xxxcq1 小时前
Go微服务网关开发(2):路由转发功能的实现
后端