场景:成绩是一个拼接字符串
姓名:张 ,学号:123,成绩:'1,2,3,4,5'
类:student
name
studentId
grade1
grade2
grade3
grade4
grade5
需要将对应数据注入到相应的成绩值当中,我这里是已经排序好的,
只要将第一个放入grade1,以此类推
1.利用JSON转化来注入
studentRoundCourseSetCommentVo:基础STUDENT数据
姓名:张 ,学号:123,成绩:'1,2,3,4,5'
if(StringUtils.isNotEmpty(studentRoundCourseSetCommentVo.getScoreDetail())){
String scoreDetail = studentRoundCourseSetCommentVo.getScoreDetail();
String[] split = scoreDetail.split(",");
int times = 1;
ObjectMapper mapper = new ObjectMapper();
String jsonStr = null;
// 将原有的对象转成JSON
try {
jsonStr = mapper.writeValueAsString(studentRoundCourseSetCommentVo);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
// 将属性名拼接后放入JSON中
for (String s : split){
String extString = Integer.toString(times);
String fieldName = "score" + extString;
jsonObject.put(fieldName,s);
times++;
}
// 由JSON再转化回原本的类
studentRoundCourseSetCommentVo =
JSONObject.parseObject(JSON.toJSONBytes(jsonObject),
StudentRoundCourseSetCommentDetailVo.class);
}
2.利用JAVA反射来注入
String scoreDetail = studentRoundCourseSetCommentVo.getScoreDetail();
String[] split = scoreDetail.split(",");
int times = 1;
for (String s : split){
String extString = Integer.toString(times);
String fieldName = "score" + extString;
times++;
try {
Field field =
studentRoundCourseSetCommentVo.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(studentRoundCourseSetCommentVo,s);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
这样在相同属性名较多时,可以节约大量时间