2013-10-26 115 views
1

我正在使用restsharp和newtonsoft.json來與我的Python API進行通信。JSON字典結果使用RestSharp/Newtonsoft.Json進行反序列化。

通訊工作正常。處理返回簡單字符串的基本查詢,所以這不是問題。

我有更復雜的結果反序列化的問題,我第一次這樣做。

因此,從網絡服務點我是回以下JSON結構:在我的C#PROGRAMM

{ 
    "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" 
    } 
] 
} 
在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); 

...返回空。我想問題是我返回一個字典「員工」,而不僅僅是單一的數據行。我需要如何設計它才能正確地反序列化?

回答

0

看起來比我想象的要簡單。 我將「Employee」類重命名爲「EmployeeData」(僅爲了提高與json參數名稱的兼容性&)。

然後我定義的第二類:

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

然後

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

回報填寫正確類員工的名單。 Trivial。 Json.net真的很強大。

相關問題