所以我只需要一个简单的Web API,它返回JSON格式,如下所示
{
"dailyDealId": "432",
"discountPercentage": "0",
"product": {
"productId": "10",
"brandId": "10",
"departmentId": "3",
"name": "Baby Girl Velour Tunic & Snowflake Legging Set",
"description": "The pretty set",
"url": "http://whatever.whatever.com/files/whatever.tif"
}
}
我想在我的C#控制台代码上获取这些数据
这是我的Model Class Data.cs
class Data
{
public string dailyDealId { get; set; }
public string discountPercentage { get; set; }
public Array product { get; set; }
}
这是我的主要代码
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://whatever.com/");
HttpResponseMessage response = client.GetAsync("product/").Result;
if (response.IsSuccessStatusCode)
{
var products = response.Content.ReadAsAsync<IEnumerable<Data>>().Result;
foreach (var p in products)
{
Console.WriteLine("dailyDealId" + p.dailyDealId);
}
}
}
但它似乎没有工作,我得到Newtonsoft.Json.JsonSerializationException:无法反序列化当前的JSON错误,任何帮助将不胜感激
由于
答案 0 :(得分:6)
一个问题可能是,当您作为示例提供给我们的JSON是一个对象时,您的类Data
会将成员product
视为Array
这一事实(包含在{{{ 1}}不在{}
)。
您需要创建一个新类并更改[]
的类型:
Data.product
public class Product
{
public string productId { get; set; }
public string brandId { get; set; }
public string departmentId { get; set; }
public string name { get; set; }
public string description { get; set; }
public string url { get; set; }
}
public class Data
{
public string dailyDealId { get; set; }
public string discountPercentage { get; set; }
public Product product { get; set; }
}
应该使用此定义。