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);
相关推荐
袋鱼不重25 分钟前
我的神奇同事,AI 用多了居然写了个 Open In Codex
前端·后端·ai编程
用户83562907805128 分钟前
使用 Python 操作 Word 内容控件
后端·python
像我这样帅的人丶你还29 分钟前
啥? 前端也要会干Java?🛵🛵🛵
后端
Hommy8831 分钟前
【剪映小助手】添加贴纸接口(Add Sticker)
后端·github·剪映小助手·视频剪辑自动化·剪映api
CaffeinePro1 小时前
FastAPI响应处理:返回值、状态码、响应头与异常标准化与案例解析
后端
HuanYu1 小时前
PageHelper分页的原理
后端
于先生吖1 小时前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
张不才2 小时前
一个静默吞数据的时间戳陷阱
后端
李少兄2 小时前
从原理到实战:Spring IoC/DI 核心知识体系与高频面试题全解
java·后端·spring
ServBay2 小时前
ServBay 1.30.0 更新:双平台引入 MCP 服务,AI 编程助手成为全栈本地运维
后端·ai编程