[英]Newtonsoft.Json serialize using property value as root name
I have to serialize a list of objects in Json in C#, I'm using Newtonsoft.Json I need to use the name value of the objects as the root name, like this: 我必须使用C#在Json中序列化对象列表,我使用的是Newtonsoft.Json,我需要使用对象的名称值作为根名称,如下所示:
"employees" :
{
"John" :
{
"id" : 18,
"email" : "john@email.com"
},
"Jack" :
{
"id" : 21,
"email" : "jack@email.com"
}
}
Where John and Jack are the values of the name property for my employees John和Jack是我的员工的name属性的值
Not the best solution but quick You can use dictionary before serialization like this 不是最好的解决方案,而是快速的方法您可以像这样在序列化之前使用字典
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; }
}
}
Output: 输出:
{"employees":{"1":{"Id":1,"Email":"1"},"2":{"Id":2,"Email":"2"},"3":{"Id":2,"Email":"3"}}}
You can find more information here https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm I think you can solve this in more elegant way using JsonConverterAttribute but it can be not easy 您可以在这里找到更多信息https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm我认为您可以使用JsonConverterAttribute以更优雅的方式解决此问题,但这并不容易
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.