0

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:

"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

Alfredo Torre
  • 678
  • 1
  • 9
  • 25
  • 1
    Can you explain why you need that kind of structure to represent something that can be an array of employees with a name property ? – PMerlet Dec 07 '17 at 15:42
  • These are the specifications that I have – Alfredo Torre Dec 07 '17 at 15:43
  • Possible duplicate of [C# JSON.NET - Deserialize response that uses an unusual data structure](https://stackoverflow.com/questions/39461518/c-sharp-json-net-deserialize-response-that-uses-an-unusual-data-structure) – Matt Spinks Dec 07 '17 at 15:47
  • can't you challenge the specs? Makes much more sense as an array. – ADyson Dec 07 '17 at 16:09

1 Answers1

1

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

Alex Lyalka
  • 1,484
  • 8
  • 13