我正在尝试使用 Newtonsoft.Json
将 json 反序列化为自定义类列表。
这是我的代码:
public List<EmployeeModel> getEmployee()
{
string Baseurl = "http://dummy.restapiexample.com/api/v1/";
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
var EmpResponse = new List<EmployeeModel>();
var Res = client.GetAsync("employees");
Res.Wait();
var result = Res.Result;
//Checking the response is successful or not which is sent using HttpClient
if (result.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var r = result.Content.ReadAsStringAsync().Result;
EmpResponse = JsonConvert.DeserializeObject<List<EmployeeModel>>(r);
//Deserializing the response recieved from web api and storing into the Employee list
}
//returning the employee list to view
return EmpResponse;
}
}
当我检查变量 r 值时,我得到以下 Json 字符串:
[
{
"id": "317",
"employee_name": "Nitza",
"employee_salary": "775",
"employee_age": "1",
"profile_image": ""
},
{
"id": "318",
"employee_name": "Nitza Ivri",
"employee_salary": "10000",
"employee_age": "33",
"profile_image": ""
}
]
另外,我的模型代码如下:
public class EmployeeModel
{
public string id { get; private set; }
public string employee_name { get; private set; }
public string employee_salary { get; private set; }
public string employee_age { get; private set; }
}
原因是您在 EmployeeModel 中的属性具有私有集。您需要从属性中删除私有,然后它才能成功反序列化。您的实体应如下所示:
public class EmployeeModel
{
public string id { get; set; }
public string employee_name { get; set; }
public string employee_salary { get; set; }
public string employee_age { get; set; }
}
此外,您的EmployeeModel
不包含属性profile_image
。您需要将此属性添加到模型中。
如果将属性资源库保持为私有很重要,则可以提供一个具有如下参数的构造函数:
public class EmployeeModel
{
public EmployeeModel(string id, string employee_name,string employee_salary, string employee_age, string profile_image )
{
this.id = id;
this.employee_name = employee_name;
this.employee_salary = employee_salary;
this.employee_age = employee_age;
this.profile_image = profile_image;
}
public string id { get; private set; }
public string employee_name { get; private set; }
public string employee_salary { get; private set; }
public string employee_age { get; private set; }
public string profile_image { get; private set; }
}