使用场景
当我们返回给前端所需的对象数据时,大多数情况可以直接使用 StructMap 映射实现自动转换,但碰到对象中的某些字段需要从 Integer 类型转换成对应枚举的时候,在 StructMap 中就需要单独对这些字段添加转换注解,实现较为麻烦,故整合出了一个通用转换工具类。
ConverUtils 工具类实现
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class ConvertUtils { // 普通对象转换 public static <T> T toObject(Object o, Class<T> tClass) { return JacksonUtils.from(JacksonUtils.to(o), tClass); } // List 对象转换 public static <T> List<T> toListOject(List list, Class<T> tClass) { if (CollectionUtil.isEmpty(list)) { return Collections.emptyList(); } List<T> result = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { result.add(JacksonUtils.from(JacksonUtils.to(list.get(i)), tClass)); } return result; } // 此处使用的 com.github.pagehelper 分页 分页对象转换 public static <T> PageResult<T> toPageOject(PageInfo pageInfo, Class<T> clazz) { if (pageInfo == null || CollectionUtil.isEmpty(pageInfo.getList())) { return new PageResult<T>(0, 20, 1, Collections.emptyList()); } List<T> from = toListOject(pageInfo.getList(), clazz); return new PageResult<T>(pageInfo.getTotal(), pageInfo.getPageSize(), pageInfo.getPageNum(), from); } }
调用方式举例
复制代码
1
2
3
4
5
6
7
8
9
10
11
12public class EnterprisePageVO { @ApiModelProperty(value = "学生id") private Long id; @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "性别") private SexEnum importOrgId; @ApiModelProperty(value = "考试科目") private List<SubjectEnum> importOrgId; } StudentVO student = ConvertUtils.toObject(studentDTO, StudentVO.class);
最后
以上就是超帅仙人掌最近收集整理的关于解决:对象映射时 Integer 类型字段转换枚举处理麻烦的全部内容,更多相关解决:对象映射时内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复