我有嵌套JSON,如 -
"disks" : [ {
"name" : "v2.16",
"diskAggregate" : "aggr0",
"diskRPM" : 15000,
"totalSizeBytes" : 1077477376,
"vendorId" : "NETAPP ",
"usedBytes" : 1070071808,
"diskType" : "FCAL",
"uuid" : "4E455441:50502020:56442D31:3030304D:422D465A:2D353230:32353836:30303030:00000000:00000000",
"portName" : "FC:A ",
"raidGroup" : "rg0"
},
{
"name" : "v4.16",
"diskAggregate" : "aggr0",
"diskRPM" : 15000,
"totalSizeBytes" : 1077477376,
"vendorId" : "NETAPP ",
"usedBytes" : 1070071808,
"diskType" : "FCAL",
"uuid" : "4E455441:50502020:56442D31:3030304D:422D465A:2D353230:32353633:34333030:00000000:00000000",
"portName" : "FC:B ",
"raidGroup" : "rg0"
}]
我希望得到额外的' totalSizeBytes'从上面的对象列表。
我使用以下代码来获取它 -
val storageDevices = "above given json".toList
val totalCapacity = storageDevices.foldLeft(0) {
case (sumOfAllDevices, storageDevice) =>
val sumOfTotalBytesOnStorageDevice = storageDevice.disks.foldLeft(0) {
case (totalBytesOnDevice, disk) =>
totalBytesOnDevice + disk.usedBytes.getOrElse(0).toString.toInt
}
sumOfAllDevices + sumOfTotalBytesOnStorageDevice
// Logger.info("dss"+sumOfTotalBytesOnStorageDevice.toString.toInt)
}
此代码以整数格式提供总容量。但由于磁盘阵列中的对象太多,totalCapacity将超过int。所以我想在添加时将其转换为Long。
我想要关注输出 -
"totalCapacity": [
{
"name": "192.168.20.22",
"y": 123456789
}
]
如何将其转换为Long以获得所有' totalBytesAvailable'的完全总和从数组/列表???
答案 0 :(得分:1)
在0L
和Int
中将零值转换为foldLeft(0L)
(默认情况下假定为getOrElse(0L)
),因此编译器将在Long
上强制执行算术添加}。