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);
相关推荐
weixin_4250230026 分钟前
Spring Boot + MyBatis Plus JOIN 分页多表查询项目文档
spring boot·后端·mybatis
sxlishaobin43 分钟前
Spring Bean生命周期详解
java·后端·spring
肉丸滚球1 小时前
飞算 JavaAI 转 SpringBoot 项目沉浸式体验:高效开发在线图书借阅平台
java·spring boot·后端
问道飞鱼3 小时前
【Rust编程语言】Rust数据类型全面解析
开发语言·后端·rust·数据类型
泉城老铁3 小时前
目前开源架构需要注意的安全问题
spring boot·后端
ZoeGranger3 小时前
【Spring】IoC 控制反转、DI 依赖注入、配置文件和bean的作用域
后端
马卡巴卡3 小时前
分库分表数据源ShardingSphereDataSource的Connection元数据误用问题分析
后端
superman超哥3 小时前
仓颉动态特性探索:反射API的原理、实战与性能权衡
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉动态特性·反射api
骑着bug的coder3 小时前
第7讲:索引(下)——失效场景与优化实战
后端·mysql
superman超哥4 小时前
仓颉元编程之魂:宏系统的设计哲学与深度实践
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·仓颉语言特性