在C#中创建模型类?

use*_*595 0 c# rest json json.net asp.net-web-api

所以我只是有一个简单的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"
}
Run Code Online (Sandbox Code Playgroud)

}

我想在我的C#控制台代码上获取这些数据

这是我的Model Class Data.cs

class Data
{
    public string dailyDealId { get; set; }
    public string discountPercentage { get; set; }
    public Array product { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的主要代码

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);
            }


        }

    }
Run Code Online (Sandbox Code Playgroud)

但它似乎没有工作,我得到Newtonsoft.Json.JsonSerializationException:无法反序列化当前的JSON错误,任何帮助将不胜感激

谢谢

Sim*_*ger 6

一个问题可能是您的课其实Data对待成员product作为Array当你给我们作为一个例子,JSON是一个对象(括在{}不在[]).

您需要创建一个新类并更改以下类型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; }
}
Run Code Online (Sandbox Code Playgroud)

JsonConvert 应该使用这个定义.