将map装换为javabean对象***将List<Map<String,Object>>转换为List<T>
controller里面的调用
@Login
@PostMapping(value = "/save")
@ApiOperation("新增用户课程")
public R save(@RequestBody Map<String, Object> map, @LoginUser UserEntity userEntity)
throws InstantiationException, IllegalAccessException {
Map<String, Object> map1 = (Map<String, Object>) map.get("data");
List<UserCouserPeriods> list = BeanMapUtils.mapsToObjects((List<Map<String, Object>>) map1.get("periods"),
UserCouserPeriods.class);
//System.out.println(list);
List<UserCourseEntity> list1 = BeanMapUtils.mapsToObjects((List<Map<String, Object>>) map1.get("courses"),
UserCourseEntity.class);
//工具类
package net.wkang.common.utils;
import com.google.common.collect.Lists;
import net.wkang.common.exception.RRException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
/**
* Created by wolf on 2018/4/9.
*/
public class BeanMapUtils {
/**
* 将map装换为javabean对象
* @param map
* @param bean
* @return
*/
public static <T> T mapToBean(Map<String, Object> map,T bean) {
try {
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
if (value==null){
return null;
}
if (!(value instanceof String)){
throw new RRException("只支持字符串转换!");
}
String str = (String)value;
if (str.trim().equals("")){
return null;
}
SimpleDateFormat sd = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN);
try {
return sd.parse(str);
} catch (ParseException e) {
throw new RRException(e.getMessage());
}
}
},java.util.Date.class);
BeanUtils.populate(bean,map);
} catch (Exception e) {
throw new RRException(e.getMessage());
}
return bean;
}
/**
* 将List<Map<String,Object>>转换为List<T>
* @param maps
* @param clazz
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,Class<T> clazz) throws InstantiationException, IllegalAccessException {
List<T> list = Lists.newArrayList();
if (maps != null && maps.size() > 0) {
Map<String, Object> map = null;
T bean = null;
for (int i = 0,size = maps.size(); i < size; i++) {
map = maps.get(i);
bean = clazz.newInstance();
mapToBean(map, bean);
list.add(bean);
}
}
return list;
}
}