业务中遇到,使用Mybatis generator生成的Example和Mapper从数据库查询结果,该结果使用的实体类是和数据库字段一一对应的,可是不想把该实体类的全部属性都返回给前端,因而新建一个实体类,其中只有前端须要的属性,而后想把List<UserA>中的对象所有拷贝到List<UserB>中,其中UserA属性多,UserB属性少,字段名是同样的。前端
方法1:使用Spring的BeanUtils.copyProperties()或者PropertyUtils.copyProperties()java
将List1循环,将UserA中须要的属性Set到UserB中。这个方法略麻烦,由于还须要循环,而且建立新对象。数据库
方法2:借助FastJson的Json和对象转换的功能json
具体实现就是,将对象(或者List)转换为json,而后再将json信息转换为指定的对象(或者指定对象的List),具体代码贴在下面:app
/** * 从List<A> copy到List<B> * * @param list * @param clazz * @param <T> * @return */ public static <T> List<T> copy(List<?> list, Class<T> clazz) { String oldOb = JSON.toJSONString(list); return JSON.parseArray(oldOb, clazz); } /** * 从对象A copy到 对象B * * @param ob A * @param clazz B.class * @return B */ public static <T> T copy(Object ob, Class<T> clazz) { String oldOb = JSON.toJSONString(ob); return JSON.parseObject(oldOb, clazz); }
Refer:https://blog.csdn.net/hw120219/article/details/89536440.net