首页 > 解决方案 > Java Spring中的对数组特定对象求和

问题描述

我如何在我的响应 json 中对 java 中的特定数组求和。

{
      "ResponA": {
        "SumA": "1000000"
      },
      "Respon B": [
      {
        "PaymentB": "Tax 2021",
        "SumB": "50"
      },
      {
        "PaymentB": "Tax 2020",
        "SumB": "20"
      }
      ],
    
      "ResponC": [
      {
        "PaymentC": "groceries 2020",
        "SumC": "10"
      },
      {
        "PaymentC": "groceries 2021",
        "SumC": "20"
      }
      ]
    }

我想总结“响应 A + 所有阵列响应 B + 所有阵列响应 C”

这是我获取json响应的代码。

String ResponA = respon.getBody().ResponA().SumA();
String ResponB = respon.getBody().ResponB().get(0).SumB();
String ResponC = respon.getBody().ResponC().get(0).SumC();

标签: javaarraysobjectsum

解决方案


您需要做两件事才能在那里得到答案。你需要知道的是

  • 如何迭代列表(在这种情况下为循环或流)
  • 如何将字符串转换为整数 (Integer.parseInt(String))
  • 另外,当您在 Java 中定义变量时,请使用camelCase,因为这是标准。

使用上面提到的东西。您应该能够计算总和。以下是您的问题的一种伪代码。

int total = 0;
total = convert responA string to int(Integer.parseInt(responA)) + total;
//write a for each loop to calculate ResponB values
for (ResponB res: respon.getBody().ResponB()){
   total = total + Integer.parseInt(res.sumB());
}
//write another for each loop to calculate ResponC values
for each (ResponC res: respon.getBody().ResponC()){
   total = total + Integer.parseInt(res.sumC());
}
//now you have. the total
System.out.println(total);

推荐阅读