1

我正在使用 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);

...返回一个空值。我想问题是我返回一个字典“员工”,而不仅仅是单个数据行。我需要如何设计它以正确反序列化它?

4

1 回答 1

0

看起来它比我想象的要简单。我将“Employee”类重命名为“EmployeeData”(只是为了优雅和与 json 参数名称的兼容性)。

然后我定义了第二类:

class EmployeeList
    {
        [JsonProperty("Employee")]
        public List<EmployeeData> Employee { get; set; }
    }

接着

JsonConvert.DeserializeObject<EmployeeList>(response.Content);

返回正确填写的包含员工列表的班级。琐碎的。Json.net 真的很强大。

于 2013-10-27T10:03:13.330 回答