文章目录
一、解决属性名太多问题
方式一:hibernate映射
hibernate自动生成映射关系文件,请点击这里
二、解决属性赋值问题
方式一:Gson
添加Gson的jar包依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6</version>
<!--<scope>compile</scope>-->
</dependency>
Mybean = gson.fromJson(message, Mybean .class);
方式二:fastjson
JSON.parseObject(json,Mybean.class)
方式三:BeanUtils
1.BeanUtils.populate()
Map->bean
public class WebBeanUtils {
// 泛型
// 到时候你用什么对象都可以了,所以用了泛型,不局限于某个对象
public static <T> T copyParamToBean(Map properties, T bean) {
try {
// 将所有参数注入到指定对象中去
// 需要对线改的set方法存在 且名字 要一致才行
BeanUtils.populate(bean, properties);
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}
}
Map集合:
Map<String, Object> properties = new HashedMap();
properties.put("testAllVisibility", exam.getTestAllVisibility());
// 试卷成绩可见性
properties.put("markVisiblity", exam.getMarkVisiblity());
// 开启作弊
properties.put("formalExam", formalExam);
// 参加考试学生
ArrayList<UserDto> students = course.getStudents();
properties.put("members", students);
// 参考人数
properties.put("memberSize", students.size())
// 最后这样子就全部注入进去了
WebBeanUtils.copyParamToBean(properties, new ItemExam());
2.BeanUtils.copyProperties()
spring的springframework的包,其中有一个BeanUtils的类,BeanUtils.copyProperties(Object source,Object target)可以实现两个对象属性值的复制,但是两个对象的属性名要一致