通过属性名,向对象的属性注入数据

场景:成绩是一个拼接字符串

姓名:张 ,学号: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);
            }
        }

这样在相同属性名较多时,可以节约大量时间

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值