目录

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);
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
大鸡腿同学3 分钟前
人生加减法之道
后端
Asthenia041223 分钟前
深入剖析 Netty 的 ByteBuf:设计思路与 ByteBuffer 的对比
后端
Asthenia041232 分钟前
Netty:EventLoop、Channel与ChannelHandller
后端
Asthenia041239 分钟前
面试复盘:文件描述符与 select、poll、epoll 的那些事儿
后端
阿黄学技术1 小时前
深入了解Spring事务及其使用场景
java·后端·spring
Asthenia04121 小时前
Netty优势/应用场景/高性能体现/BIO,NIO,AIO/Netty序列化
后端
Y第五个季节2 小时前
Spring AOP
java·后端·spring
xjz18422 小时前
基于SpingBoot3技术栈的微服务系统构建实践
后端
省长2 小时前
Sa-Token v1.41.0 发布 🚀,来看看有没有令你心动的功能!
java·后端·开源
全栈智擎2 小时前
Java高效开发实战:10个让代码质量飙升的黄金法则
后端·程序员