Home > Net >  Sum Array Specific Object In Java Spring
Sum Array Specific Object In Java Spring

Time:09-17

How can i sum the spesific array in java here my respon 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"
      }
      ]
    }

i want to sum "Respon A All Array Respon B All Array Respon C"

and heres my code for getting the json respon.

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

CodePudding user response:

There are min 2 things you need to do to get the answer there. Things you need to know is

  • How to iterate a list (for loops or streams in this case)
  • How to convert String to Integer (Integer.parseInt(String))
  • extra, when you define variables in Java use camelCase, as this is the standard.

using above mentioned things. You should be able to calculate the sum. Following is kind of a pseudo code for your problem.

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);
  • Related