Counting JSON nodes
How to calculate the how many objects in JSON object my code is
String json = IOUtils.toString(is);
JSONObject jo = new JSONObject(json);
Here 'jo' is the jsonobeject with in that object some data is there that data is:
{
"cargoDetails":[{
"noOfPackages":"2",
"packType":"AUG",
"uom":"LB",
"packLength":"10",
"actualWt":"5",
"packHeight":"2",
"packWidth":"4",
"packDescription":"description",
"currId":"1",
"shipmentMode":"1"},
{"noOfPackages":"2",
"packType":"BAG",
"uom":"KG",
"packLength":"10",
"actualWt":"5",
"packHeight":"2",
"packWidth":"4",
"packDescription":"description",
"currId":"1",
"shipmentMode":"1"}],
"type":"air",
"userId":"KOTESWAR",
"customerId":"CUST00168",
"contractId":"CONTRACT0000576",
"originTerminalId":"FINBOM",
"destinationTerminalId":"FINDEL",
"ShipperId":"CUST00003",
"serviceLevelId":"STD",
"paymentTerms":"Prepaid",
"terminalId":"FINBOM",
"originDepartment":"AE",
"destinationDepartment":"AI",
"departurePort":"INBOM",
"destinationPort":"BOM",
"totalNoPcs":"4",
"totalActualWt":"5",
"totalVol":"10"
}
k with in that i can send cargodetails objects 2 remaining are bookingdetails so my question is how to find the how many objects are there in jO. because with that jo only i can iterate the loop.
If you are asking about how to define how many keys are in object, you should use Object.keys(json), which returns an array with all own keys. Yet, it is rather new function, not implemented in all browsers that are currently in use. Without Object.keys you have to use (for key in json)
loop, testing each key with hasOwnProperty
.
By the way, hasOwnProperty also can be not implemented in some browsers.
精彩评论