利用反射调用实体对象的get方法,get方法的方法名根据实体类的属性名生成
/**
* 封装json数据
* @param resumes
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public String generate(List<Resume> resumes) {
// 实体类的字段名和json串中的字段名的映射关系存储在数据表中,将字段映射表中的数据放入map中
Map<String, String> mstColumnReferenceMap = new HashMap<>();
List<MstColumnReference> mstColumnReferenceList = mstColumnReferenceRepository.findAllByOrderByIdAsc();
for (MstColumnReference mstColumnReference : mstColumnReferenceList) {
mstColumnReferenceMap.put(mstColumnReference.getTableColumn(), mstColumnReference.getJobColumn());
}
List<Map<String, Object>> resumeJsonList = new ArrayList<>();
for(Resume resume : resumes) {
Map<String, Object> map = new HashMap<>();
for(Map.Entry<String,String> entity : mstColumnReferenceMap.entrySet()) {
String fieldName = entity.getKey();
// 根据属性名生成get方法的方法名
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
String[] str = getMethodName.split("_");
// 去掉中间的下划线
if (str.length > 1) {
StringBuilder sb = new StringBuilder();
sb.append(str[0]);
for (int i = 1; i < str.length; ++i) {
sb.append(str[i].substring(0, 1).toUpperCase() + str[i].substring(1));
}
getMethodName = sb.toString();
}
try {
Class tCls = resume.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
Object value = getMethod.invoke(resume, new Object[]{});
String textValue = null;
if(value != null) {
if (value instanceof Date) {
// 处理日期格式的属性
Date date = (Date) value;
textValue = DateUtil.formartDate(date);
} else {
//其它数据类型都当作字符串简单处理
textValue = value.toString();
}
} else {
textValue = "";
}
map.put(entity.getValue(), textValue);
} catch (Exception e) {
log.warn("【字段映射错误, 字段名:{}->{}】", entity.getKey(), entity.getValue());
log.warn("错误信息:{}", e.getMessage());
}
}
resumeJsonList.add(map);
}
return EsbServiceUtil.objectToJson(resumeJsonList);
}
参考文章:https://blog.youkuaiyun.com/panpan96/article/details/76566475