我正在使用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; }
另外class包含一个构造函数,但我认为这不是问题。
现在,只需致电:
var Data = JsonConvert.DeserializeObject<Employee>(response.Content);
...返回null。我想问题是我返回一个字典“Employee”,而不仅仅是单个数据行。我如何设计它以正确反序列化?
答案 0 :(得分:0)
看起来比我想象的要简单。 我将“Employee”类重命名为“EmployeeData”(仅为了优雅和与json参数名称的兼容性)。
然后我定义了第二类:
class EmployeeList
{
[JsonProperty("Employee")]
public List<EmployeeData> Employee { get; set; }
}
然后
JsonConvert.DeserializeObject<EmployeeList>(response.Content);
返回正确填充的类,其中包含员工列表。 不重要的。 Json.net非常强大。