简体   繁体   English

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

[英]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.

相关问题 使用Newtonsoft.Json序列化不带属性名称的Dictionary - Serialize Dictionary without property name with Newtonsoft.Json 使用 Newtonsoft.Json 将名称反序列化为值 - Deserialize a name as a value using Newtonsoft.Json 使用Newtonsoft.Json跳过序列化JSON对象的属性名称 - Skip Serializing the the Property Name for a JSON Object using Newtonsoft.Json Newtonsoft.Json 用于反序列化的自定义根名称 - Newtonsoft.Json Custom Root Name for Deserialization NewtonSoft.Json 序列化和反序列化具有 IEnumerable 类型属性的类<ISomeInterface> - NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface> Newtonsoft.JSON 忽略父属性但序列化子属性 - Newtonsoft.JSON Ignore parent property but serialize child properties C#使用Newtonsoft.json对仅一个属性(找不到根)反序列化Json响应 - C# Deserialize Json response for only one property (could't find root) using Newtonsoft.json 如何使用 Newtonsoft.Json 将类型信息从 object 序列化为 json? - How to serialize object to json with type info using Newtonsoft.Json? 使用 Newtonsoft.Json 库时无法序列化 ISession - Cannot serialize ISession when using Newtonsoft.Json library 如何使用newtonsoft.json序列化图形模型中的特定属性? - How to serialize specific properties in graph model using newtonsoft.json?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM