互轉的前提是屬性名相同,如果屬性名不同,又要互轉,只能自已手寫工具類了
1、pom
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
2、map轉實體類,如果屬性里有list會出錯
Map<String, String> 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<String, String> describe = BeanUtils.describe(studentVO); // 如果屬性里有list會出錯
也可以用fastjson去轉換
1、pom
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.69</version>
</dependency>
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<String,String> hashMap = JSONObject.parseObject(map, HashMap.class);