2014-10-07 33 views
0

我有嵌套JSON一樣 -如何使用scala和play來獲取長格式的嵌套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 
    } 
] 

如何將其轉換爲長的時間從陣列/列表中的所有「totalBytesAvailable」的確切數額???

回答

1

鑄造零個值作爲0L(默認假定Int),無論是在foldLeft(0L)getOrElse(0L),所以編譯器將強制執行上Long算術加法。

相關問題