簡體   English   中英

Newtonsoft.Json使用屬性值作為根名稱進行序列化

[英]Newtonsoft.Json serialize using property value as root name

我必須使用C#在Json中序列化對象列表,我使用的是Newtonsoft.Json,我需要使用對象的名稱值作為根名稱,如下所示:

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

John和Jack是我的員工的name屬性的值

不是最好的解決方案,而是快速的方法您可以像這樣在序列化之前使用字典

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以更優雅的方式解決此問題,但這並不容易

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM