marius_ll
marius_ll

Reputation: 163

How to get array from JSON Object?

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    }

Upvotes: 6

Views: 45114

Answers (5)

Rajkumar
Rajkumar

Reputation: 96

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"));
    }
}

Upvotes: 8

Oguz
Oguz

Reputation: 1926

You can use GSON lib. Here you can download.

public static void parseJson(String sb){

 JsonParser jsonParser = new JsonParser();
 JsonObject jo = (JsonObject)jsonParser.parse(sb);
 JsonArray jArray = jo.getAsJsonArray("value"); // get json array

 Gson gJson = new Gson();
 ArrayList jsonObjArrayList = gJson.fromJson(jArray, ArrayList.class);


 for (int i = 0; i< jsonObjArrayList.size(); i++){
    System.out.println(jsonObjArrayList.get(i).toString());
 }
}

Upvotes: 0

marius_ll
marius_ll

Reputation: 163

Thanks for the help. The Problem was the StringBuffer. I have used the .toString function of StringBuffer and everything works.

Upvotes: 0

Tanmay Delhikar
Tanmay Delhikar

Reputation: 1387

Well, it works for me in my environment. Add " ]} " at the end.

enter image description here

Upvotes: 1

PotatoManager
PotatoManager

Reputation: 1775

Considering the JSON

{  "@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    } ]}

Addind ]} to the JSON makes it valid and the code in the question should be able to parse it.

Upvotes: 0

Related Questions