我必须在c#中的json中序列化对象列表,我正在使用newtonsoft.json我需要使用对象的名称值作为根名称,例如:
"employees" :
{
"John" :
{
"id" : 18,
"email" : "john@email.com"
},
"Jack" :
{
"id" : 21,
"email" : "jack@email.com"
}
}
约翰和杰克是我员工的名称属性的价值
不是最好的解决方案,而是快速的解决方案您可以在序列化之前使用字典
class Example
{
static void Main()
{
var l = new[]
{
new Employee {Id = 1, Name = "1", Email = "1"},
new Employee {Id = 2, Name = "2", Email = "2"},
new Employee {Id = 2, Name = "3", Email = "3"}
};
var s = JsonConvert.SerializeObject(new { employees = l.ToDictionary(x => x.Name, x => x) });
}
class Employee
{
public int Id { get; set; }
[JsonIgnore]
public string Name { get; set; }
public string Email { get; set; }
}
}
输出:
{"employees":{"1":{"Id":1,"Email":"1"},"2":{"Id":2,"Email":"2"},"3":{"Id":2,"Email":"3"}}}
您可以在此处找到更多信息https://www.newtonsoft.com/json/help/html/serializatizationattributes.htm,我认为您可以使用JSONCONCONVERTRIBUTE以更优雅的方式解决此问题