【问题标题】:How do I deserialize the JSON response into my list?如何将 JSON 响应反序列化到我的列表中?
【发布时间】:2019-07-19 18:58:46
【问题描述】:

我想解析以下 JSON 响应:

{
  "message": "string",
  "errorCode": "string",
  "totalSize": 0,
  "offset": 0,
  "done": true,
  "nextRecordsUrl": "string",
  "records": [
    {
      "id": "string",
      "name": "string",
      "external_ID_vod__c": "string",
      "vExternal_Id_vod__c": "string"
    }
  ]
}

**注意有多个“记录”

我用来反序列化 JSON 响应的相关类是:

public class RecordProduct
        {
            public string id { get; set; }
            public string name { get; set; }
            public string external_ID_vod__c { get; set; }
            public string vExternal_Id_vod__c { get; set; }
        }

public class Products
        {
            public string message { get; set; }
            public string errorCode { get; set; }
            public int totalSize { get; set; }
            public int offset { get; set; }
            public bool done { get; set; }
            public string nextRecordsUrl { get; set; }
            public List<RecordProduct> records { get; set; }

        }

调用 API 的代码:

public void getAllProductInfo()
        {
            RestClient client = new RestClient("blahblahblah/");

            RestRequest request = new RestRequest("/api/Products", Method.GET);

            string securityToken = getBearerToken();
            request.AddHeader("Accept", "application/json");
            request.AddHeader("Authorization", "Bearer " + securityToken);

            IRestResponse<JsonResponseSetup.Datum.Products> response = client.Execute<JsonResponseSetup.Datum.Products>(request);

            var res = response.Data.records;
            res.ForEach(Console.WriteLine);

         }

当我执行最后一行时:res.ForEach(Console.WriteLine); 我没有得到要打印的记录。

编辑:我想通了。我只是错误地访问了记录的成员。 以下代码代替了我的代码的最后两行。

foreach(var item in response.Data.records)
{
   Console.WriteLine($"name: {item.name}, id: {item.id}");
}

【问题讨论】:

    标签: c# json restsharp json-deserialization


    【解决方案1】:

    Newtonsoft 是一个易于使用的框架,可帮助您在 .NET 和 JSON 对象之间进行转换,正如您将在文档中的 this example 中看到的那样。

    简而言之,您只需将 JSON 传递给 DeserializeObject 方法并指定对应的 JSON 应解析到哪个类。

    【讨论】:

    • 我认为在新的 RestSharp 中,他们已经删除了对该框架的依赖。您链接的示例也非常基本,我对解析为列表更感兴趣。
    【解决方案2】:

    试试这个

    Products facebookFriends = new JavaScriptSerializer().Deserialize<Products>(result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      相关资源
      最近更新 更多