我正在使用 restsharp 和 newtonsoft.json 来与我的 Python API 通信。
通讯工作正常。处理返回简单字符串的基本查询,所以这不是问题。
我对更复杂的结果的反序列化有问题,我是第一次这样做。
因此,从 Web 服务的角度来看,我返回以下 json 结构:
{
"Employee": [
{
"Department.DepartmentName": "IT",
"Employee.EmployeeArchived": 0,
"Employee.EmployeeDepartmentId": 13,
"Employee.EmployeeFired": 0,
"Employee.EmployeeId": 1,
"Employee.EmployeeName": "Name1",
"Employee.EmployeePID": 292,
"Employee.EmployeeSurname": "Surname1"
},
{
"Department.DepartmentName": "IT",
"Employee.EmployeeArchived": 0,
"Employee.EmployeeDepartmentId": 4,
"Employee.EmployeeFired": 0,
"Employee.EmployeeId": 2,
"Employee.EmployeeName": " Name2",
"Employee.EmployeePID": 50,
"Employee.EmployeeSurname": " Surname2"
}
]
}
在我的 C# 程序中的 response.contents(RestClient.Execute 的结果)中,我得到了类似的内容(我将其截断为一个数据行):
{\n \"Employee\": [\n {\n \"Department.DepartmentName\": \"EDV\", \n \"Employee.EmployeeArchived\": 0, \n \"Employee.EmployeeDepartmentId\": 13, \n \"Employee.EmployeeFired\": 0, \n \"Employee.EmployeeId\": 1, \n \"Employee.EmployeeName\": \"Name1\", \n \"Employee.EmployeePID\": 292, \n \"Employee.EmployeeSurname\": \"Surname1\"\n }
到目前为止,它看起来不错。
现在。我试图将我的数据类定义为能够反序列化它,如下所示:
public class Employee
{
[JsonProperty("Department.DepartmentName")]
public string Department { get; set; }
[JsonProperty("Employee.EmployeeName")]
public string Name {get; set;}
[JsonProperty("Employee.EmployeeSurname")]
public string Surname { get; set; }
[JsonProperty("Employee.EmployeeArchived")]
public int Archived { get; set; }
[JsonProperty("Employee.EmployeeFired")]
public int Fired { get; set; }
[JsonProperty("Employee.EmployeeId")]
public int Id { get; set; }
[JsonProperty("Employee.EmployeeDepartmentId")]
public int DepId { get; set; }
[JsonProperty("Employee.EmployeePID")]
public int PID { get; set; }
另外类包含一个构造函数,但我认为这不是问题。
现在,只需调用:
var Data = JsonConvert.DeserializeObject<Employee>(response.Content);
...返回一个空值。我想问题是我返回一个字典“员工”,而不仅仅是单个数据行。我需要如何设计它以正确反序列化它?