java - 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();
解决方案
您需要做两件事才能在那里得到答案。你需要知道的是
- 如何迭代列表(在这种情况下为循环或流)
- 如何将字符串转换为整数 (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);
推荐阅读
- react-native - Typeerror:React-native android中的网络请求失败
- javascript - 如何在角度单元测试中对服务进行单元测试?
- html - Heroku 应用程序崩溃 - 不提供静态 html 内容(Express 服务器)
- maven - 在 Visual Studio 代码中将 Evosuite 插件添加到 Maven 项目时缺少工件 ID
- angular - Typescript - html 模板上的“找不到名称”错误
- gcc - 如何构建仅包含库中选定符号的可重定位二进制文件?
- node.js - 如何在 Microsoft Teams Bot 中进行身份验证后获取用户访问令牌?
- android - 房间从特定 ID 的最新输入数据中检索特定数据
- hibernate - 运行 micronaut 1.3.3 尝试创建简单的应用程序得到休眠错误
- android - 长按后如何检测按钮的释放?