i want to get the array of json objects from a json object. But it doesnt work. Can anybody help me?
The output is:
Exception in thread "main" org.json.JSONException: JSONObject["value"] not
found.
Source Code:
import org.json.*;
public class JsonIO {
public static void parseJson(StringBuffer sb){
JSONObject obj = new JSONObject(sb);
JSONArray arr = obj.getJSONArray("value");
for (int i = 0; i< arr.length(); i++){
System.out.println(arr.getJSONObject(i).getString("Name"));
}
}
}
The input is:
{ "@odata.context":"https://www.nameofshop......de/odata/$metadata#Product","value":[ { "ProductTypeId":5,"ParentGroupedProductId":0,"VisibleIndividually":true,"Name":"Build your own computer","ShortDescription":"Build it","FullDescription":"<p>Fight back against cluttered workspaces with the stylish IBM zBC12 All-in-One desktop PC, featuring powerful computing resources and a stunning 20.1-inch widescreen display with stunning XBRITE-HiColor LCD technology. The black IBM zBC12 has a built-in microphone and MOTION EYE camera with face-tracking technology that allows for easy communication with friends and family. And it has a built-in DVD burner and Sony's Movie Store software so you can create a digital entertainment library for personal viewing at your convenience. Easy to setup and even easier to use, this JS-series All-in-One includes an elegantly designed keyboard and a USB mouse.</p>","AdminComment":null,"ProductTemplateId":1,"VendorId":0,"ShowOnHomePage":true,"MetaKeywords":null,"MetaDescription":null,"MetaTitle":null,"AllowCustomerReviews":true,"ApprovedRatingSum":0,"NotApprovedRatingSum":0,"ApprovedTotalReviews":0,"NotApprovedTotalReviews":0,"SubjectToAcl":false,"LimitedToStores":false,"Sku":null,"ManufacturerPartNumber":null,"Gtin":null,"IsGiftCard":false,"GiftCardTypeId":0,"OverriddenGiftCardAmount":null,"RequireOtherProducts":false,"RequiredProductIds":null,"AutomaticallyAddRequiredProducts":false,"IsDownload":false,"DownloadId":0,"UnlimitedDownloads":false,"MaxNumberOfDownloads":0,"DownloadExpirationDays":null,"DownloadActivationTypeId":0,"HasSampleDownload":false,"SampleDownloadId":0,"HasUserAgreement":false,"UserAgreementText":null,"IsRecurring":false,"RecurringCycleLength":0,"RecurringCyclePeriodId":0,"RecurringTotalCycles":0,"IsRental":false,"RentalPriceLength":0,"RentalPricePeriodId":0,"IsShipEnabled":true,"IsFreeShipping":true,"ShipSeparately":false,"AdditionalShippingCharge":0.0000,"DeliveryDateId":0,"IsTaxExempt":false,"TaxCategoryId":2,"IsTelecommunicationsOrBroadcastingOrElectronicServices":false,"ManageInventoryMethodId":1,"UseMultipleWarehouses":false,"WarehouseId":0,"StockQuantity":10000,"DisplayStockAvailability":true,"DisplayStockQuantity":false,"MinStockQuantity":0,"LowStockActivityId":1,"NotifyAdminForQuantityBelow":1,"BackorderModeId":0,"AllowBackInStockSubscriptions":false,"OrderMinimumQuantity":1,"OrderMaximumQuantity":10000,"AllowedQuantities":null,"AllowAddingOnlyExistingAttributeCombinations":false,"DisableBuyButton":false,"DisableWishlistButton":false,"AvailableForPreOrder":false,"PreOrderAvailabilityStartDateTimeUtc":null,"CallForPrice":false,"Price":1200.0000,"OldPrice":0.0000,"ProductCost":0.0000,"SpecialPrice":null,"SpecialPriceStartDateTimeUtc":null,"SpecialPriceEndDateTimeUtc":null,"CustomerEntersPrice":false,"MinimumCustomerEnteredPrice":0.0000,"MaximumCustomerEnteredPrice":0.0000,"BasepriceEnabled":false,"BasepriceAmount":0.0000,"BasepriceUnitId":0,"BasepriceBaseAmount":0.0000,"BasepriceBaseUnitId":0,"MarkAsNew":true,"MarkAsNewStartDateTimeUtc":null,"MarkAsNewEndDateTimeUtc":null,"HasTierPrices":false,"HasDiscountsApplied":false,"Weight":2.0000,"Length":2.0000,"Width":2.0000,"Height":2.0000,"AvailableStartDateTimeUtc":null,"AvailableEndDateTimeUtc":null,"DisplayOrder":0,"Published":true,"Deleted":true,"CreatedOnUtc":"2016-04-19T11:41:10.163+01:00","UpdatedOnUtc":"2016-04-19T11:41:10.163+01:00","ProductType":"SimpleProduct","BackorderMode":"NoBackorders","DownloadActivationType":"0","GiftCardType":"Virtual","LowStockActivity":"DisableBuyButton","ManageInventoryMethod":"ManageStock","RecurringCyclePeriod":"Days","RentalPricePeriod":"Days","Id":1 },{ "ProductTypeId":5,"ParentGroupedProductId":0,"VisibleIndividually":true,"Name":"Digital Storm VANQUISH 3 Custom Performance PC","ShortDescription":"Digital Storm Vanquish 3 Desktop PC","FullDescription":"<p>Blow the doors off today\u2019s most demanding games with maximum detail, speed, and power for an immersive gaming experience without breaking the bank.</p><p>Stay ahead of the competition, VANQUISH 3 is fully equipped to easily handle future upgrades, keeping your system on the cutting edge for years to come.</p><p>Each system is put through an extensive stress test, ensuring you experience zero bottlenecks and get the maximum performance from your hardware.</p>","AdminComment":null,"ProductTemplateId":1,"VendorId":0,"ShowOnHomePage":false,"MetaKeywords":null,"MetaDescription":null,"MetaTitle":null,"AllowCustomerReviews":true,"ApprovedRatingSum":0,"NotApprovedRatingSum":0,"ApprovedTotalReviews":0,"NotApprovedTotalReviews":0,"SubjectToAcl":false,"LimitedToStores":false,"Sku":null,"ManufacturerPartNumber":null,"Gtin":null,"IsGiftCard":false,"GiftCardTypeId":0,"OverriddenGiftCardAmount":null,"RequireOtherProducts":false,"RequiredProductIds":null,"AutomaticallyAddRequiredProducts":false,"IsDownload":false,"DownloadId":0,"UnlimitedDownloads":false,"MaxNumberOfDownloads":0,"DownloadExpirationDays":null,"DownloadActivationTypeId":0,"HasSampleDownload":false,"SampleDownloadId":0,"HasUserAgreement":false,"UserAgreementText":null,"IsRecurring":false,"RecurringCycleLength":0,"RecurringCyclePeriodId":0,"RecurringTotalCycles":0,"IsRental":false,"RentalPriceLength":0,"RentalPricePeriodId":0,"IsShipEnabled":true,"IsFreeShipping":false,"ShipSeparately":false,"AdditionalShippingCharge":0.0000,"DeliveryDateId":0,"IsTaxExempt":false,"TaxCategoryId":2,"IsTelecommunicationsOrBroadcastingOrElectronicServices":false,"ManageInventoryMethodId":1,"UseMultipleWarehouses":false,"WarehouseId":0,"StockQuantity":10000,"DisplayStockAvailability":true,"DisplayStockQuantity":false,"MinStockQuantity":0,"LowStockActivityId":1,"NotifyAdminForQuantityBelow":1,"BackorderModeId":0,"AllowBackInStockSubscriptions":false,"OrderMinimumQuantity":1,"OrderMaximumQuantity":10000,"AllowedQuantities":null,"AllowAddingOnlyExistingAttributeCombinations":false,"DisableBuyButton":false,"DisableWishlistButton":false,"AvailableForPreOrder":false,"PreOrderAvailabilityStartDateTimeUtc":null,"CallForPrice":false,"Price":1259.0000,"OldPrice":0.0000,"ProductCost":0.0000,"SpecialPrice":null,"SpecialPriceStartDateTimeUtc":null,"SpecialPriceEndDateTimeUtc":null,"CustomerEntersPrice":false,"MinimumCustomerEnteredPrice":0.0000,"MaximumCustomerEnteredPrice":0.0000,"BasepriceEnabled":false,"BasepriceAmount":0.0000,"BasepriceUnitId":0,"BasepriceBaseAmount":0.0000,"BasepriceBaseUnitId":0,"MarkAsNew":false,"MarkAsNewStartDateTimeUtc":null,"MarkAsNewEndDateTimeUtc":null,"HasTierPrices":false,"HasDiscountsApplied":false,"Weight":7.0000,"Length":7.0000,"Width":7.0000,"Height":7.0000,"AvailableStartDateTimeUtc":null,"AvailableEndDateTimeUtc":null,"DisplayOrder":0,"Published":true,"Deleted":true,"CreatedOnUtc":"2016-04-19T11:41:12.177+01:00","UpdatedOnUtc":"2016-04-19T11:41:12.177+01:00","ProductType":"SimpleProduct","BackorderMode":"NoBackorders","DownloadActivationType":"0","GiftCardType":"Virtual","LowStockActivity":"DisableBuyButton","ManageInventoryMethod":"ManageStock","RecurringCyclePeriod":"Days","RentalPricePeriod":"Days","Id":2 }
You can access the array values by using the index number: x = myObj. rights[0];
Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.
jsonObject. put("key", "value"); Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
' { } ' used for Object and ' [] ' is used for Array in json.
The exception occurred because your input JSON string is not properly assigned to JSONObject. There is no constructor like JSONObject(StringBuffer). Just Change it to JSONObject(String) or JSONObject(StringBufferObject.toString())
also, add ]}
at the end of your input JSON string.
public static void parseJson(StringBuffer sb) throws JSONException {
JSONObject obj = new JSONObject(sb.toString());
JSONArray arr = obj.getJSONArray("value");
for (int i = 0; i < arr.length(); i++) {
System.out.println(arr.getJSONObject(i).getString("Name"));
}
}
Well, it works for me in my environment. Add " ]}
" at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With