一个不愿透露姓名的糕
2019-08-08 15:53
采纳率: 33.3%
浏览 552

我有这么一个json字符串通过fastjson的parse方法接的 我有什么办法遍历他们

我有这么一个json字符串通过fastjson的parse方法接的
我有什么办法遍历他们并且我要用对应的每个(edyear-bgyear)*money
然后累加

{"bgyear1":"2019","edyear2":"2019","edyear3":"2019","edyear1":"2019","Money3":"33333","Money1":"11111","Money2":"2222","bgyear2":"2019","bgyear3":"2019"}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • baichangda234 2019-08-08 18:28
    已采纳

    图片说明

    如上图,代码如下

    //1、定义json数据
            String json="{\"bgyear1\":\"2019\",\"edyear2\":\"2019\",\"edyear3\":\"2019\",\"edyear1\":\"2019\",\"Money3\":\"33333\",\"Money1\":\"11111\",\"Money2\":\"2222\",\"bgyear2\":\"2019\",\"bgyear3\":\"2019\"}";
            //2、解析
            JSONObject jsonObject= JSONObject.parseObject(json);
            Map<String,Integer> resMap=new HashMap<>();
            //3、从1开始,依次循环取出json中字段
            for(int i=1;;i++){
                Integer edyear = jsonObject.getInteger("edyear"+i);
                Integer bgyear = jsonObject.getInteger("bgyear"+i);
                Integer money = jsonObject.getInteger("Money"+i);
                //3.1、如果任一字段为null,则打断循环
                if(edyear==null||bgyear==null||money==null){
                    break;
                }
                //3.2、添加结果
                resMap.put("res"+i,(edyear-bgyear)*money);
            }
            //4、打印结果(注意此处使用的是jdk1.8语法lambda表达式)
            resMap.forEach((k,v)->{
                System.out.println(k+":"+v);
            });
    
    点赞 打赏 评论
  • weixin_40852944 2019-08-08 16:56
    String jsons = "{\"bgyear1\":\"2019\",\"edyear2\":\"2019\",\"edyear3\":\"2019\",\"edyear1\":\"2019\",\"Money3\":\"33333\",\"Money1\":\"11111\",\"Money2\":\"2222\",\"bgyear2\":\"2019\",\"bgyear3\":\"2019\"}";
            JSONObject jsonObject = JSON.parseObject(jsons);
            jsonObject.entrySet().forEach(V->{
                System.out.println(V);
            });
    
    点赞 打赏 评论
  • tkzc_shark 2019-08-08 17:19

    String str = "{\"bgyear1\":\"2019\",\"edyear2\":\"2019\",\"edyear3\":\"2019\",\"edyear1\":\"2019\",\"Money3\":\"33333\",\"Money1\":\"11111\",\"Money2\":\"2222\",\"bgyear2\":\"2019\",\"bgyear3\":\"2019\"}";
    JSONObject obj = JSON.parseObject(str);
    int edyear1 = Integer.parseInt(obj.get("edyear1").toString());
    int bgyear1 = Integer.parseInt(obj.get("bgyear1").toString());
    int money1 = Integer.parseInt(obj.get("Money1").toString());
    int result = (edyear1 - bgyear1) * money1;

    点赞 打赏 评论

相关推荐 更多相似问题