我正在使用Newtonsoft json序列化程序将json字符串转换为对象。我有如下 json 结构 -
{
"EmployeeRecords": {
"12": {
"title": "Mr",
"Name": "John"
},
"35":{
"title": "Mr",
"Name": "Json"
}
}
}
我希望这个Json被塞进下面的班级——
public class Employee
{
public string EmployeeNumber { get; set; }
public string title { get; set; }
public string Name { get; set; }
}
public class EmployeeRecords
{
public List<Employee> Employees { get; set; }
}
这里的员工编号是 12 和 35。
请指导我如何编写自定义服务器,它将从父节点读取员工编号并将其包含在子节点的 EmployeeNumber 属性中。
您可以反序列化为字典,然后在循环中分配 EmployeeNumbers。
public class DataModel
{
public Dictionary<string, Employee> EmployeeRecords { get; set; }
}
反序列化后的数字断言:
var records = JsonConvert.DeserializeObject<DataModel>(json);
foreach (var item in records.EmployeeRecords)
{
item.Value.EmployeeNumber = item.Key;
}
你可以用 LINQ to JSON(JObject
和朋友)轻松地做到这一点。下面是一个简短但完整的示例:
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
public class Employee
{
public string EmployeeNumber { get; set; }
public string title { get; set; }
public string Name { get; set; }
public JProperty ToJProperty()
{
return new JProperty(EmployeeNumber,
new JObject {
{ "title", title },
{ "Name", Name }
});
}
}
public class EmployeeRecords
{
public List<Employee> Employees { get; set; }
public JObject ToJObject()
{
var obj = new JObject();
foreach (var employee in Employees)
{
obj.Add(employee.ToJProperty());
}
return new JObject {
new JProperty("EmployeeRecords", obj)
};
}
}
class Test
{
static void Main()
{
var records = new EmployeeRecords {
Employees = new List<Employee> {
new Employee {
EmployeeNumber = "12",
title = "Mr",
Name = "John"
},
new Employee {
EmployeeNumber = "35",
title = "Mr",
Name = "Json"
},
}
};
Console.WriteLine(records.ToJObject());
}
}
它可能不是最简单的代码(如果你愿意改变你的结构,Ufuk 的方法很棒),但它显示了一切的可定制性。