使用場景
當我們回傳給前端所需的物件資料時,大多數情況可以直接使用 StructMap 映射實作自動轉換,但碰到物件中的某些欄位需要從 Integer 型別轉換成對應列舉的時候,在 StructMap 中就需要單獨對這些欄位添加轉換注解,實作較為麻煩,故整合出了一個通用轉換工具類,
ConverUtils 工具類實作
public 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);
}
}
呼叫方式舉例
public class EnterprisePageVO {
@ApiModelProperty(value = "https://www.cnblogs.com/pandacode/p/學生id")
private Long id;
@ApiModelProperty(value = "https://www.cnblogs.com/pandacode/p/姓名")
private String name;
@ApiModelProperty(value = "https://www.cnblogs.com/pandacode/p/性別")
private SexEnum importOrgId;
@ApiModelProperty(value = "https://www.cnblogs.com/pandacode/p/考試科目")
private List<SubjectEnum> importOrgId;
}
StudentVO student = ConvertUtils.toObject(studentDTO, StudentVO.class);
本文來自博客園,作者:這個殺手冷死了,轉載請注明原文鏈接:https://www.cnblogs.com/pandacode/p/16171437.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/459500.html
標籤:Java
