Newtonsoft.Json使用属性值作为根名称进行序列化

时间:2017-12-07 15:37:01

标签: c# json json.net

我必须在C#中序列化Json中的对象列表,我使用Newtonsoft.Json 我需要使用对象的名称值作为根名称,如下所示:

"employees"  :
  {
    "John" :
      {
        "id" : 18,
        "email" : "john@email.com"
       },
    "Jack" :
       {
         "id" : 21,
         "email" : "jack@email.com"
        }
   }

John和Jack是我的员工姓名属性的值

1 个答案:

答案 0 :(得分:1)

不是最好的解决方案,但很快 您可以在序列化之前使用字典

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/SerializationAttributes.htm我认为您可以使用JsonConverterAttribute以更优雅的方式解决此问题,但这可能并不容易