首页 > 解决方案 > 将 JSON 反序列化为对象列表 (RestSharp)

问题描述

我似乎无法弄清楚为什么每次我执行 GET 请求并尝试将数据从 JSON 反序列化到对象列表时它都没有值(NULL)。如果我输出 response.content 我得到整个 JSON(在尝试反序列化之前)。

    {
      "Information": [
        {
          "Name": "Samuel",
          "ID": "samJ",
          "Sales": "5-A",
          "FoodChoice": [
            "Hamburger",
            "Hotdog"
          ]
        },
        {
          "Name": "James",
          "ID": "jamesJ",
          "Sales": "5-B",
          "FoodChoice": [
            "Salsa",
            "Salad"
          ]
        }
    ]
}

这是我正在尝试使用的代码

var client = new RestClient("pretendAPI");
var request = new RestRequest(Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
IRestResponse response = client.Execute(request);


var data = JsonConvert.DeserializeObject<JsonModel>(response.Content);
Console.WriteLine(data.details[0].Id); <--- NULL

这些是我试图将数据放入的对象

public class JsonModel
{
    public List<Users> details { get; set; }
}

public class Users
{
    public string Name;
    public string ID;
    public string Sales;
    public List<string> FoodChoice;
}

标签: c#jsonrestsharp

解决方案


推荐阅读