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);
相关推荐
七月丶3 分钟前
🛠 用 Node.js 和 commander 快速搭建一个 CLI 工具骨架(gix 实战)
前端·后端·github
七月丶6 分钟前
🔀 打造更智能的 Git 提交合并命令:gix merge 实战
前端·后端·github
异常君13 分钟前
深入剖析 Redis 集群:分布式架构与实现原理全解
redis·分布式·后端
silenceper26 分钟前
如何使用Golang开发MCP服务器:从mcp-go到mcp-k8s实践
后端
Delphi菜鸟37 分钟前
go环境安装mac
开发语言·后端·golang
蜗牛_snail1 小时前
SpringBoot项目动态加载jar 实战级别
spring boot·后端·jar
CodeSheep3 小时前
JetBrains再出手,最新IntelliJ IDEA 2025.1正式登场!
前端·后端·github
七月丶3 小时前
🚀 从 Git 操作痛点出发,我为什么开发了 gix?
前端·后端·github
知其然亦知其所以然3 小时前
大模型时代,Java开发者别落伍!LangChain4j让你轻松追上
java·人工智能·后端