【发布时间】:2016-02-13 05:02:41
【问题描述】:
问题背景:
我正在调用亚马逊产品广告 API,并从他们的服务接收 JSON 格式的产品列表。
问题:
遗憾的是,JSON 响应因提供给 API 的参数而异。例如:搜索“体育用品”对“手表”的响应略有不同。
下面给出了一个非常简单的差异示例:
从 API 接收到的体育用品 JSON:
{
"Item": {
"ID": "145",
"Title": "Football",
"ImageUrl": "http://amazon.com/football.jpg",
"Shipping": "UK",
"ListPrice": "7.99"
}
}
观察从 API 接收到的 JSON:
{
"Item": {
"ID": "567",
"Title": "RolexWatch",
"ImageUrl": "http://amazon.com/RolexWatch.jpg",
"Shipping": "UK",
"ListPrice": "£7000.00",
"SalePrice": "£6500.00" <------------- extra item in Watches JSON
}
}
我目前正在使用 NewtonSoft 将两个响应反序列化为两个不同的 C# 模型,即:
public class SportingGoods
{
public string ID {set;get;}
public string Title {set;get;}
public string ImagesUrl {set;get;}
public string Shipping{set;get;}
public string ListPrice{set;get;}
}
public class Watches
{
public string ID {set;get;}
public string Title {set;get;}
public string ImagesUrl {set;get;}
public string Shipping{set;get;}
public string ListPrice{set;get;}
public string SalePrice{set;get;}
}
我发现来自 Amazon API 的 JSON 响应还有其他变化。 当 JSON 数据变化如此之大时,如何正确处理这种反序列化?当我不能 100% 确定 JSON 会是什么样子时,我无法继续创建不同的模型。
【问题讨论】: