2015-11-22 41 views
0

問題背景:反序列化JSON - 處理財產,可以是一個數組

我查詢亞馬遜產品廣告API,並試圖desearlize JSON響應到C#對象。

的問題:

當代碼試圖轉換我收到了反序列化錯誤。儘管我不能確定哪個部分導致了錯誤。下面顯示我收到的錯誤:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type'System.Collections.Generic.List`1[ShoppingComparisonEngine.AWS.AwsCommon.Item]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. 

Path 'Items.Item.ASIN', line 1, position 612. 

代碼:

下面的C#是什麼Newtonsoft試圖序列化。

Item.cs:

public class Item 
{ 
    [JsonProperty("asin")] 
    public string ASIN { get; set; } 
    [JsonProperty("parentasin")] 
    public string ParentASIN { get; set; } 
    [JsonProperty("detailpageurl")] 
    public string DetailPageURL { get; set; } 
    [JsonProperty("salesrank")] 
    public string SalesRank { get; set; } 
    [JsonProperty("smallimage")] 
    public SmallImage SmallImage { get; set; } 
    [JsonProperty("mediumimage")] 
    public MediumImage MediumImage { get; set; } 
    [JsonProperty("largeimage")] 
    public LargeImage LargeImage { get; set; } 
    [JsonProperty("imagesets")] 
    public ImageSets ImageSets { get; set; } 
    [JsonProperty("itemattributes")] 
    public ItemAttributes ItemAttributes { get; set; } 
    [JsonProperty("offersummary")] 
    public OfferSummary OfferSummary { get; set; } 
    [JsonProperty("offers")] 
    public Offers Offers { get; set; } 
} 

Items.cs:

public class Items 
{ 
    [JsonProperty("totalresults")] 
    public string TotalResults { get; set; } 
    [JsonProperty("totalpages")] 
    public string TotalPages { get; set; } 
    [JsonProperty("moresearchresultsurl")] 
    public string MoreSearchResultsUrl { get; set; } 
    [JsonProperty("item")] 
    public List<Item> Item { get; set; } 
} 

JSON:

我相信這是一個事實我有燒灼項目的問題,而轉換需要他們的名單?

{ 
"Items": { 
    "xmlns": "http://webservices.amazon.com/AWSECommerceService/2011-08-01", 
    "Request": { 
     "IsValid": "True", 
     "ItemSearchRequest": { 
      "Availability": "Available", 
      "Condition": "New", 
      "ItemPage": "6", 
      "Keywords": "champagne bucket", 
      "ResponseGroup": [ 
       "Medium", 
       "Offers" 
      ], 
      "SearchIndex": "HomeGarden" 
     } 
    }, 
    "TotalResults": "51", 
    "TotalPages": "6", 
    "MoreSearchResultsUrl": "http://www.amazon.co.uk/gp/redirect.html?linkCode=xm2&SubscriptionId=AKIAIFERUZJXWJ3Y2USA&location=http%3A%2F%2Fwww.amazon.co.uk%2Fgp%2Fsearch%3Fkeywords%3Dchampagne%2Bbucket%26url%3Dsearch-alias%253Doutdoor&tag=compar0c2-21&creative=12734&camp=2025", 
    "Item": { 
     "ASIN": "B00IYO4HRQ", 
     "DetailPageURL": "http://www.amazon.co.uk/Bottle-Holder-Accessories-Garden-Maintenance/dp/B00IYO4HRQ%3FSubscriptionId%3DAKIAIFERUZJXWJ3Y2USA%26tag%3Dcompar0c2-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00IYO4HRQ", 
     "ItemLinks": { 
      "ItemLink": [ 
       { 
        "Description": "Add To Wishlist", 
        "URL": "http://www.amazon.co.uk/gp/registry/wishlist/add-item.html%3Fasin.0%3DB00IYO4HRQ%26SubscriptionId%3DAKIAIFERUZJXWJ3Y2USA%26tag%3Dcompar0c2-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D12734%26creativeASIN%3DB00IYO4HRQ" 
       }, 
       { 
        "Description": "Tell A Friend", 
        "URL": "http://www.amazon.co.uk/gp/pdp/taf/B00IYO4HRQ%3FSubscriptionId%3DAKIAIFERUZJXWJ3Y2USA%26tag%3Dcompar0c2-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D12734%26creativeASIN%3DB00IYO4HRQ" 
       }, 
       { 
        "Description": "All Customer Reviews", 
        "URL": "http://www.amazon.co.uk/review/product/B00IYO4HRQ%3FSubscriptionId%3DAKIAIFERUZJXWJ3Y2USA%26tag%3Dcompar0c2-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D12734%26creativeASIN%3DB00IYO4HRQ" 
       }, 
       { 
        "Description": "All Offers", 
        "URL": "http://www.amazon.co.uk/gp/offer-listing/B00IYO4HRQ%3FSubscriptionId%3DAKIAIFERUZJXWJ3Y2USA%26tag%3Dcompar0c2-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D12734%26creativeASIN%3DB00IYO4HRQ" 
       } 
      ] 
     }, 
     "SmallImage": { 
      "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL._SL75_.jpg", 
      "Height": { 
       "Units": "pixels", 
       "value": "75" 
      }, 
      "Width": { 
       "Units": "pixels", 
       "value": "75" 
      } 
     }, 
     "MediumImage": { 
      "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL._SL160_.jpg", 
      "Height": { 
       "Units": "pixels", 
       "value": "160" 
      }, 
      "Width": { 
       "Units": "pixels", 
       "value": "160" 
      } 
     }, 
     "LargeImage": { 
      "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL.jpg", 
      "Height": { 
       "Units": "pixels", 
       "value": "300" 
      }, 
      "Width": { 
       "Units": "pixels", 
       "value": "300" 
      } 
     }, 
     "ImageSets": { 
      "ImageSet": [ 
       { 
        "Category": "swatch", 
        "SwatchImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31lBLzzkQlL._SL30_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "30" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "30" 
         } 
        }, 
        "SmallImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31lBLzzkQlL._SL75_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "75" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "75" 
         } 
        }, 
        "ThumbnailImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31lBLzzkQlL._SL75_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "75" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "75" 
         } 
        }, 
        "TinyImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31lBLzzkQlL._SL110_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "110" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "110" 
         } 
        }, 
        "MediumImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31lBLzzkQlL._SL160_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "160" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "160" 
         } 
        }, 
        "LargeImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31lBLzzkQlL.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "300" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "300" 
         } 
        } 
       }, 
       { 
        "Category": "primary", 
        "SwatchImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL._SL30_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "30" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "30" 
         } 
        }, 
        "SmallImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL._SL75_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "75" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "75" 
         } 
        }, 
        "ThumbnailImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL._SL75_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "75" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "75" 
         } 
        }, 
        "TinyImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL._SL110_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "110" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "110" 
         } 
        }, 
        "MediumImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL._SL160_.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "160" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "160" 
         } 
        }, 
        "LargeImage": { 
         "URL": "http://ecx.images-amazon.com/images/I/31cr9r7XChL.jpg", 
         "Height": { 
          "Units": "pixels", 
          "value": "300" 
         }, 
         "Width": { 
          "Units": "pixels", 
          "value": "300" 
         } 
        } 
       } 
      ] 
     }, 
     "ItemAttributes": { 
      "Brand": "Garden at Home", 
      "EAN": "5971458914919", 
      "EANList": { 
       "EANListElement": "5971458914919" 
      }, 
      "Feature": "Wine Bottle Holder and Cooler Bag Wine Accessories", 
      "Label": "Outdoor&Lawn", 
      "Manufacturer": "Outdoor&Lawn", 
      "MPN": "GG_89773368", 
      "PartNumber": "GG_89773368", 
      "ProductGroup": "Lawn & Patio", 
      "ProductTypeName": "OUTDOOR_LIVING", 
      "Publisher": "Outdoor&Lawn", 
      "Studio": "Outdoor&Lawn", 
      "Title": "Wine Bottle Holder and Cooler Bag Wine Accessories, Garden, Lawn, Maintenance" 
     }, 
     "OfferSummary": { 
      "LowestNewPrice": { 
       "Amount": "5220", 
       "CurrencyCode": "GBP", 
       "FormattedPrice": "£52.20" 
      }, 
      "TotalNew": "1", 
      "TotalUsed": "0", 
      "TotalCollectible": "0", 
      "TotalRefurbished": "0" 
     }, 
     "Offers": { 
      "TotalOffers": "1", 
      "TotalOfferPages": "1", 
      "MoreOffersUrl": "http://www.amazon.co.uk/gp/offer-listing/B00IYO4HRQ%3FSubscriptionId%3DAKIAIFERUZJXWJ3Y2USA%26tag%3Dcompar0c2-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D12734%26creativeASIN%3DB00IYO4HRQ", 
      "Offer": { 
       "OfferAttributes": { 
        "Condition": "New" 
       }, 
       "OfferListing": { 
        "OfferListingId": "kif7varXuUaD7y55JfdjU7h3YCJvQokyXfgDIWvxOx6%2FqiMbxoPBsyFWCmgo8pbOqZNcezFUCBSdlx3JtRpEpe4Tu7VGv9zncLOYVmoSOUEDNQf1rrKJzZVCjnVPRCKyes0GSlEzlx%2Faht4%2FtjijlvCo14Z3CCcm", 
        "Price": { 
         "Amount": "5800", 
         "CurrencyCode": "GBP", 
         "FormattedPrice": "£58.00" 
        }, 
        "SalePrice": { 
         "Amount": "5220", 
         "CurrencyCode": "GBP", 
         "FormattedPrice": "£52.20" 
        }, 
        "AmountSaved": { 
         "Amount": "580", 
         "CurrencyCode": "GBP", 
         "FormattedPrice": "£5.80" 
        }, 
        "PercentageSaved": "10", 
        "Availability": "Usually dispatched within 1-2 business days", 
        "AvailabilityAttributes": { 
         "AvailabilityType": "now", 
         "MinimumHours": "24", 
         "MaximumHours": "48" 
        }, 
        "IsEligibleForSuperSaverShipping": "0", 
        "IsEligibleForPrime": "0" 
       } 
      } 
     }, 
     "EditorialReviews": { 
      "EditorialReview": { 
       "Source": "Product Description", 
       "Content": "Ice Bucket Bag and Wine Cooler This unique Ice Bucket Bag is attractive and very durable. It is ideal for transporting wine to a friend, hostess or party and arriving with it perfectly chilled.Transparent and waterproof, this wine or Champagne bag also makes a super, space-saving ice bucket that simply folds away after use. It is especially ideal for a picnic or BBQ as it can fold for easy transport and is unbreakableIn addition, this bag makes a great party favor - comes with pocket for place card, business card or gift card. Heavy duty plastic measures 4\" x 4\" x 10\" when open, gift card slot measures 2\" x 3\".", 
       "IsLinkSuppressed": "0" 
      } 
     } 
    } 
} 

編輯

這是我用來創建一個轉換器來同時處理一個單一的項目對象,它們的列表的代碼。

public class ItemConverter:JsonConverter 
{ 
    public override bool CanConvert(Type objectType) 
    { 
     throw new NotImplementedException(); 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     if (reader.TokenType == JsonToken.StartArray) 
     { 
      List<Item> items = serializer.Deserialize<List<Item>>(reader); 

      return items; 
     } 
     else 
     { 
      Item itemList = serializer.Deserialize<Item>(reader); 
      return new List<Item>(new[] { itemList }); 
     } 
    } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

向我們展示JSON,沒有我們無法幫助的。 – DavidG

+0

@DavidG添加了JSON響應 – user1352057

+0

它看起來像'Item'屬性不是一個列表,使它成爲一個普通對象:'public Item Item {get;組; }' – DavidG

回答

2

JSON中的Item屬性是一個普通對象,而不是對象列表。如果它被認爲是一個列表,那麼JSON將被包含在方括號,表明它是一個數組,例如:

"Item": [{ item1 }, { item2}, ... ] 

所以,你需要改變你的模式相匹配。例如:

public class Items 
{ 
    //snip 
    public Item Item { get; set; } 
} 
+0

感謝您的回覆。我擁有的問題通常是檢索項目列表。在這種情況下,它看起來是一個單一的問題? – user1352057

+0

那麼這個JSON不是一個列表,所以是的,這是問題。也許有不同的API調用呈現不同的JSON。 – DavidG

+0

@ DavidG非常感謝您的幫助。我最終得到了這個排序。正如我所說的,有時候Items屬性是一個單數對象,其他的時候是一個數組。最後,我利用NewtonSoft中的JsonConverter類創建了一個轉換器。我將把代碼添加到原始問題中。 – user1352057

2

淨小提琴:https://dotnetfiddle.net/9MACjN

你有多個問題:

  • 你實際上是缺少您的JSON收盤}

  • 你需要反序列化到包含Items父類(例如,Response)。

  • Items.Item屬性需要是Item而不是List<Item>,正如David所說。

  • JsonProperty屬性根本不需要。

然後它工作。

+0

我認爲OP已經序列化爲'Items',否則會出現不同的錯誤。這些屬性也不是問題,儘管它們是多餘的。 – DavidG

+0

@DavidG,好的,我更新了修復程序。這是多個問題。 – toddmo

+0

@toddmo謝謝你的回覆。是的,我錯過了最後一個{在我的JSON中。 AWS響應的工作方式有時會返回項目列表,其他時候它會是單個項目對象,我在問題中添加了我解決問題的方式。我將刪除多餘的JSON屬性。非常感謝您的回覆。 – user1352057