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);
相关推荐
f***a3466 小时前
SpringBoot 如何调用 WebService 接口
java·spring boot·后端
Apifox6 小时前
如何通过抓包工具快速生成 Apifox 接口文档?
前端·后端·测试
pilaf19907 小时前
Rust练习题
开发语言·后端·rust
苏禾7 小时前
静态代理与动态代理:深入理解Java代理模式
后端
vx_bisheyuange7 小时前
基于SpringBoot的交通在线管理服务系统
java·spring boot·后端·毕业设计
小坏讲微服务7 小时前
Spring Boot 4.0 与 MyBatis Plus 整合完整指南
java·spring boot·后端·mybatis·springcloud·mybatis plus·java开发
番茄Salad7 小时前
Spring Boot项目,修改项目名称,修改包名!
java·spring boot·后端
疯狂的程序猴7 小时前
Fiddler调试工具全面解析 HTTPHTTPS抓包、代理设置与接口测试实战教程
后端
极市平台7 小时前
骁龙大赛技术分享第4期来了
人工智能·经验分享·笔记·后端·个人开发
开心就好20257 小时前
Charles抓包工具使用方法 Charles抓包分析、配置教程、网络排查技巧与手机抓包步骤
后端