【问题标题】:Check, if value exists in response. eBay API [duplicate]检查响应中是否存在值。 eBay API [重复]
【发布时间】:2015-05-04 15:47:13
【问题描述】:

我在开发应用程序时遇到问题。 我正在使用 eBay API 来获取有关卖家列出的物品的信息。我使用的调用名为“GetSellerList”。

如果项目有可用的 FreeAddedCategory,则响应可能包含名为“CategoryID”(FreeAddedCategory.CategoryID) 的值。您会发现这样的 XML 作为响应:

<ItemArray>
  <Item>
    <FreeAddedCategory>
      <CategoryID>XXXXXXXXX</CategoryID>
    </FreeAddedCategory>
  </Item>
</ItemArray>

因为并不总是返回此值,所以我收到以下错误消息:

对象引用未设置为对象的实例

我现在想在使用它之前检查这个对象是否可用,以防止出现错误。这就是我开始解决问题的方式(但没有成功):

    foreach (ItemType item in apiCall.ApiResponse.ItemArray)
       {
          if (String.IsNullOrWhiteSpace(item.FreeAddedCategory.CategoryID))
                {
                    Console.WriteLine("FreeAdded: Nicht vorhanden!");
                }
        }

但此检查也会显示相同的错误消息。我该怎么做才能使代码正常工作?逻辑应该是这样的:

IF item.FreeAddedCategory.CategoryID exist
  {
      do everything that needs to be done
  }
ELSE skip;

【问题讨论】:

  • NullReferenceException 的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
  • 问题已解决。我在 Chuck 的回答下方写了我的解决方案作为评论。是的,这是一个愚蠢的初学者错误;)对不起
  • @Filz 6 年后,您的评论帮助我解决了自己的问题。谢谢!!

标签: c# xml soap nullreferenceexception


【解决方案1】:

试试:

XElement root = XElement.Load(file); // .Parse(string);
if (root.Descendants("FreeAddedCategory").Any())
{
   // do exists
}
else
{
   // doesn't exist
}

如果这对您的情况更有意义,请使用 CategoryId

【讨论】:

  • 嘿查克,感谢您的快速回复。我的错误真的很愚蠢!我不必检查“item.FreeAddedCategory.CategoryID”是否为“null”,而是只检查“item.FreeAddedCategory”。因为“item.FreeAddedCategory”一直是“null”,所以当我尝试访问“item.FreeAddedCategory.CategoryID”时确实得到了 NullReferenceException。
猜你喜欢
  • 2022-01-18
  • 2017-05-29
  • 1970-01-01
  • 2015-01-18
  • 2011-12-14
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
相关资源
最近更新 更多