首先我知道这个问题被问了好几百次,但我不知道我的问题是什么。
我试图使用NewtonSoft将json字符串反序列化为自定义对象。
var client = new RestClient(URL);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(retEmployeeFilters);
var response = client.Execute(request);
//Console.WriteLine(response.Content);
return JsonConvert.DeserializeObject<RetrieveEmployeeResponse>(response.Content);
行
Console.WriteLine(response.Content);
返回此json
{"response":[{"id":3,"name":"A","email":"sansdad32a.@ds.com","mobile_number":"41","address":"B","age":20,"role":"N","hiring_date":"2053-04-03","created_at":"2016-03-16 23:49:15","updated_at":"2016-03-16 23:49:15"},{"id":4,"name":"B","email":"sansda32d32a.@ds.com","mobile_number":"41321","address":"Q","age":20,"role":"C","hiring_date":"2053-04-03","created_at":"2016-03-16 23:49:24","updated_at":"2016-03-16 23:49:24"}]}
这里是RetrieveEmployeeResponse类
class RetrieveEmployeeResponse
{
public List<Employee> response { get; set; }
public String success { get; set; }
}
员工类
class Employee
{
public int id {get;set;}
public String name {get;set;}
public String email {get;set;}
public String mobile_number {get;set;}
public int age {get;set;}
public String address {get;set;}
public String role {get;set;}
public String hiring_date {get;set;}
}
是我做的一切吗?
调试此处返回的对象
return JsonConvert.DeserializeObject<RetrieveEmployeeResponse>(response.Content);
有response = null和success = null
任何帮助?
答案 0 :(得分:1)
通过评论中的讨论,以下代码修复了问题,但原始问题的内容仍然不清楚。如果有明确的话,我会更新这个答案。
将行return JsonConvert.DeserializeObject<RetrieveEmployeeResponse>(response.Content);
更改为以下内容,解决了返回对象中null属性的问题。
var tempStr = response.Content;
var temp = JsonConvert.DeserializeObject<RetrieveEmployeeResponse>(tempStr);
return temp;
答案 1 :(得分:0)
您应该将收到的json响应反序列化为
string responseJson="{\"response\":[{\"id\":3,\"name\":\"A\",\"email\":\"sansdad32a.@ds.com\",\"mobile_number\":\"41\",\"address\":\"B\",\"age\":20,\"role\":\"N\",\"hiring_date\":\"2053-04-03\",\"created_at\":\"2016-03-16 23:49:15\",\"updated_at\":\"2016-03-16 23:49:15\"},{\"id\":4,\"name\":\"B\",\"email\":\"sansda32d32a.@ds.com\",\"mobile_number\":\"41321\",\"address\":\"Q\",\"age\":20,\"role\":\"C\",\"hiring_date\":\"2053-04-03\",\"created_at\":\"2016-03-16 23:49:24\",\"updated_at\":\"2016-03-16 23:49:24\"}]}\r\n";
return JsonConvert.DeserializeObject<RetrieveEmployeeResponse>(responseJson);
你的json没有任何成功字符串,这就是反序列化后它为空的原因。