我正在尝试反序列化一个JSON,它从API调用中连续包含一系列“客户端”:
{"resource":[{"ClientID":1,"ClientName":"Name 1","ClientIntID":"TEST001","ClientCreatedDate":"2018-05-10 00:00:00"},{"ClientID":2,"ClientName":"Name 2","ClientIntID":"TEST002","ClientCreatedDate":"2018-05-10 03:10:47"},{"ClientID":3,"ClientName":"TestAPI","ClientIntID":"API001","ClientCreatedDate":"2018-05-10 03:30:14"},{"ClientID":4,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:03:40"},{"ClientID":5,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:28"},{"ClientID":6,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:31"},{"ClientID":7,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:32"},{"ClientID":8,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:35"}]}
进入客户列表。
这是我反序列化的代码:
IRestResponse<List<Client>> response = restClient.Execute<List<Client>>(request);
var content = response.Content;
var data = response.Data;
//Trying to check output of each Client in List:
foreach(Client c in data)
{
Console.WriteLine(c.ClientName);
}
这是我的客户类:
public class Client
{
public int ClientID { get; set; }
public string ClientName { get; set; }
public string ClientIntID { get; set; }
public string ClientCreatedDate { get; set; }
}
我得到的列表为null,但是当我将代码更改为仅转换为一个客户端时,它会正确地将第一个客户端存储在JSON响应中。
任何提示?
答案 0 :(得分:1)
您的答案采用以下格式,因此您必须反序列化为RootObject
public class Resource {
public int ClientID { get; set; }
public string ClientName { get; set; }
public string ClientIntID { get; set; }
public string ClientCreatedDate { get; set; }
}
public class RootObject{
public List<Resource> resource { get; set; }
}
答案 1 :(得分:0)
您有两种选择,
选项1:
如上所述,要么将C#类更改为<div class="a-1" href="/a/b/c/d/e/index.html">
<a class="location">text</div>
</div>
中的反序列化,RootObject
内部包含List<Resource> resource
,您可以访问该代码来遍历集合:
public class Client
{
[JsonProperty("ClientID")]
public int ClientID { get; set; }
[JsonProperty("ClientName")]
public string ClientName { get; set; }
[JsonProperty("ClientIntID")]
public string ClientIntID { get; set; }
[JsonProperty("ClientCreatedDate")]
public string ClientCreatedDate { get; set; }
}
public class Root
{
[JsonProperty("resource")]
public List<Client> Clients { get; set; }
}
现在你的C#
IRestResponse<Root> response = restClient.Execute<Root>(request);
var content = response.Content;
var data = response.Data.Clients;
//Trying to check output of each Client in List:
foreach(Client c in data)
{
Console.WriteLine(c.ClientName);
}
选项2
修改Json以删除以下Beginning - {"resource":
和End - }
,默认情况下将其设为集合而不是对象。现在您可以使用原始C#代码将数据作为例外,它将直接反序列化为List<Client>