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);
相关推荐
bobz96512 分钟前
virtio vs vfio
后端
Rexi1 小时前
“Controller→Service→DAO”三层架构
后端
bobz9651 小时前
计算虚拟化的设计
后端
深圳蔓延科技1 小时前
Kafka的高性能之路
后端·kafka
Barcke1 小时前
深入浅出 Spring WebFlux:从核心原理到深度实战
后端
JuiceFS1 小时前
从 MLPerf Storage v2.0 看 AI 训练中的存储性能与扩展能力
运维·后端
大鸡腿同学1 小时前
Think with a farmer's mindset
后端
Moonbit2 小时前
用MoonBit开发一个C编译器
后端·编程语言·编译器
Reboot2 小时前
达梦数据库GROUP BY报错解决方法
后端
稻草人22222 小时前
java Excel 导出 ,如何实现八倍效率优化,以及代码分层,方法封装
后端·架构