对 Java Spring 中的数组特定对象求和

Sum Array Specific Object In Java Spring

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

{
      "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();

您至少需要做 2 件事才能得到答案。 你需要知道的是

  • 如何迭代列表(在本例中为循环或流)
  • 如何将字符串转换为整数 (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);