2017-07-19 184 views
0

我想从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 } 
+1

你JSON是无效的 – Flown

+0

也尝试使用一些构建= IN,即GSON或杰克逊Objectmapper谁已经解决了解析JSON字符串到Java对象的问题。 – pandaadb

+0

不,它应该是工作。使用相同的JSON我已经在Rails中解析了它 –

回答

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")); 
    } 
} 
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使其有效,问题中的代码应该能够解析它。

+0

我有“]}”在JSON结束但它不起作用 –

1

那么,它适用于我的环境。最后加上“]}”。

enter image description here

0

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

0

您可以使用GSON库。在这里你可以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()); 
} 
}