【问题标题】:Creating Model Class in C#?在 C# 中创建模型类?
【发布时间】:2013-06-27 23:09:16
【问题描述】:

所以我只有一个简单的 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# 控制台代码中获取这些数据

这是我的模型类 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 错误,任何帮助将不胜感激

谢谢

【问题讨论】:

  • 响应的内容是什么? http://whatever.com/product/ 是否只返回 json 或您的网址有误?
  • url 是正确的,所以当我使用 POSTMAN 或 Soap ui 调用 url 时,它会返回我放在那里的 JSON 数据
  • 您正在调用 asynchronous 方法并期望它在返回时阻塞..
  • 那么你将如何解决它?
  • @SimonWhitehead 访问任务结果隐式等待。

标签: c# json rest asp.net-web-api json.net


【解决方案1】:

一个问题可能是您的班级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; }
}

JsonConvert 应该使用这个定义。

【讨论】:

  • 如何更改数据类型?
  • 我确实在我的回答中给了你类型。
  • 知道了,非常感谢!!
猜你喜欢
  • 2011-03-08
  • 1970-01-01
  • 2016-05-28
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多