【问题标题】:Sum Array Specific Object In Java SpringJava Spring中的对数组特定对象求和
【发布时间】:2021-11-05 17:41:38
【问题描述】:

如何在我的响应 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"
      }
      ]
    }

我想求和 "Respon A + All Array Respon B + All Array Respon C"

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

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

【问题讨论】:

    标签: java arrays object sum


    【解决方案1】:

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

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

    【讨论】:

    • 你可以改进你的 json 本身。例如。对 SumA、SumB 和 SumC 使用 int 值,那么您就不需要做所有这些 Integer.parseInt() 的事情了。无论如何,我只是对您当前的问题给出了答案。
    猜你喜欢
    • 2020-06-14
    • 2022-12-04
    • 2022-11-19
    • 2016-09-05
    • 2011-05-06
    • 2015-11-28
    • 2021-08-09
    • 1970-01-01
    • 2015-07-03
    相关资源
    最近更新 更多