/**
* 将list map转list
*
* @param maps map
* @param clazz clazz
* @param <T> T
* @return list
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
*/
public static <T> List listMap2List(List<Map<Object, ? extends T>> maps, Class<? extends T> clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
List<T> targets = null;
if (V.notEmpty(maps)) {
targets = new ArrayList<>();
for (Map map : maps) {
T target = clazz.getConstructor().newInstance();
Field[] fields = clazz.getDeclaredFields();
if (V.notEmpty(fields)) {
for (Object keyObj : map.keySet()) {
for (Field field : fields) {
if (keyObj != null && ((String) keyObj).equals(field.getName())) {
if (!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
T value = (T) map.get(keyObj);
if (value != null) {
try {
field.set(target, convertValueToFieldType(value, field));
} catch (Exception e) {
log.info("{}字段尝试转换异常", field.getName());
}
}
}
}
}
}
targets.add(target);
}
}
return targets;
}
/**
* jsonObj => list
*
* @param jsonObj jsonObj
* @param clazz clazz
* @param <T> T
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
*/
public static <T> List jsonObj2List(Object jsonObj, Class<T> clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
return listMap2List(JSON.parseObject(jsonObj.toString(), ArrayList.class), clazz);
}
/**
* 转换为field对应的类型
*
* @param value
* @param field
* @return
*/
public static Object convertValueToFieldType(Object value, Field field) throws ParseException {
String type = field.getGenericType().getTypeName();
if (value.getClass().getName().equals(type)) {
return value;
}
if (String.class.getName().equals(type)) {
return S.valueOf(value);
} else if (Integer.class.getName().equals(type)) {
return Integer.parseInt(S.valueOf(value));
} else if (Long.class.getName().equals(type)) {
return Long.parseLong(S.valueOf(value));
} else if (Double.class.getName().equals(type)) {
return Double.parseDouble(S.valueOf(value));
} else if (BigDecimal.class.getName().equals(type)) {
return new BigDecimal(S.valueOf(value));
} else if (Float.class.getName().equals(type)) {
return Float.parseFloat(S.valueOf(value));
} else if (Boolean.class.getName().equals(type)) {
return V.isTrue(S.valueOf(value));
} else if (type.contains(Date.class.getSimpleName())) {
if (value != null && value instanceof Long) {
Date date = new Date((long) value);
return date;
}
return D.fuzzyConvert(S.valueOf(value));
}
return value;
}
完美解决FastJson出现 com.alibaba.fastjson.JSONObject cannot be cast to model的bug
最新推荐文章于 2024-07-09 14:25:33 发布