如何从JSON对象获取数组?

时间:2017-07-19 09:05:25

标签: java json

我想从json对象获取json对象的数组。但它不起作用。 有人能帮助我吗?

输出结果为:

Exception in thread "main" org.json.JSONException: JSONObject["value"] not 
found.

源代码:

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

}

输入是:

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

5 个答案:

答案 0 :(得分:2)

发生异常是因为您的输入JSON字符串未正确分配给JSONObject。没有像JSONObject(StringBuffer)这样的构造函数。只需将其更改为JSONObject(String)或 的JSONObject(StringBufferObject.toString())

另外,在输入JSON字符串的末尾添加]}

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

答案 1 :(得分:1)

嗯,它适用于我的环境。最后添加“]}”。

enter image description here

答案 2 :(得分:0)

考虑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]}到JSON使它有效,问题中的代码应该能够解析它。

答案 3 :(得分:0)

感谢您的帮助。 问题是StringBuffer。我使用了StringBuffer的.toString函数,一切正常。

答案 4 :(得分:0)

您可以使用GSON lib。您可以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());
 }
}