map与实体类互转DTO、VO互转


互转的前提是属性名相同,如果属性名不同,又要互转,只能自已手写工具类了

1、pom


    commons-beanutils
    commons-beanutils
    1.9.4

2、map转实体类,如果属性里有list会出错

Map of = ImmutableMap.of("a", "aaaaa", "b", "kluowejbbbb");
Student student = new Student();
BeanUtils.copyProperties(student,of);

DTO转VO

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会出错

StudentVO studentVO = new StudentVO();
studentVO.setAge(12);
studentVO.setStudentName("jkljsie");
Map describe = BeanUtils.describe(studentVO); // 如果属性里有list会出错

也可以用fastjson去转换

1、pom


    com.alibaba
    fastjson
    1.2.69

2、先成转json再转成dto

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 hashMap = JSONObject.parseObject(map, HashMap.class);

相关