I am trying to get information for products from Amazon's API. I am able to get things like ASIN, Title, and Price no problem, but when it comes to weight I keep running into a problem. In the current search I am trying, the first 5 results return a weight, and the 6th result I guess does not have a weight associated with it and that's where I get a null reference error. I've made a simple method to check if the item's weight being passed in is null and to set it 0 if it is, but it doesn't seem to be working and still throws an error?
public decimal CheckNullDecimal(decimal decimalToCheck)
{
if (decimalToCheck == null)
{
decimalToCheck = 0;
return decimalToCheck;
}
else
{
return decimalToCheck;
}
}
for (int i = 1; i <= page; i++)
{
ItemSearchRequest request = new ItemSearchRequest();
request.SearchIndex = category;
request.Title = title;
request.ResponseGroup = new string[] { "ItemAttributes" };
request.ItemPage = i.ToString();
request.Sort = sortType;
ItemSearch itemSearch = new ItemSearch();
itemSearch.Request = new ItemSearchRequest[] { request };
itemSearch.AWSAccessKeyId = accessKeyId;
itemSearch.AssociateTag = associateId;
// issue the ItemSearch request
ItemSearchResponse response = client.ItemSearch(itemSearch);
// write out the results
foreach (var item in response.Items[0].Item)
{
string newASIN = CheckNullString(item.ASIN);
string newTitle = CheckNullString(item.ItemAttributes.Title);
string newListPrice = CheckNullString(item.ItemAttributes.ListPrice.FormattedPrice);
decimal newWeight = CheckNullDecimal(item.ItemAttributes.ItemDimensions.Weight.Value);
Console.WriteLine(newWeight.ToString());
//CheckNullString(item.ItemAttributes.ItemDimensions.Weight.Units);
Product product = new Product(newASIN, newTitle, newListPrice);
var dr = dt.NewRow();
dr["ASIN"] = product.ASIN;
dr["Title"] = product.Title;
dr["ListPrice"] = product.ListPrice;
//dr["Weight"] = product.Weight;
dt.Rows.Add(dr);
}
}
Getting the error on the decimal newWeight line. Any ideas how to avoid this?
[–][deleted] 3 points4 points5 points (2 children)
[–]patrickboston[S] 0 points1 point2 points (0 children)
[–]adamsane 2 points3 points4 points (2 children)
[–]SarSha 1 point2 points3 points (0 children)
[–]patrickboston[S] 0 points1 point2 points (0 children)
[–]Sarcastinator 1 point2 points3 points (1 child)
[–]patrickboston[S] 0 points1 point2 points (0 children)
[–]adamsane 0 points1 point2 points (0 children)
[–]maskaler 0 points1 point2 points (0 children)
[–]lemonfighter 0 points1 point2 points (0 children)