1

I am using Newtonsoft json serializer to convert json string into objects. I have json structure as below -

{
    "EmployeeRecords": {
        "12": {
            "title": "Mr",
            "Name": "John"
        },
        "35":{
            "title": "Mr",
            "Name": "Json"
        }
    }
}

I want this Json to be serilized into below class -

public class Employee
{
    public string EmployeeNumber { get; set; }
    public string title { get; set; }
    public string Name { get; set; }
}

public class EmployeeRecords
{
    public List<Employee> Employees { get; set; }
}

Here Employeenumber is 12 and 35.

Please guide me how can I write custom serilizer which will read the Employee number from parent node and include it in the child node's EmployeeNumber property.

CHash11
  • 746
  • 4
  • 14
  • 31

2 Answers2

1

You can deserialize into a dictionary, then assign the EmployeeNumbers in a loop.

public class DataModel
{
    public Dictionary<string, Employee> EmployeeRecords { get; set; }
}

Assing the numbers after deserialization:

var records = JsonConvert.DeserializeObject<DataModel>(json);

foreach (var item in records.EmployeeRecords)
{
    item.Value.EmployeeNumber = item.Key;
}
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
0

You can easily do this with LINQ to JSON (JObject and friends). Here's a short but complete example:

using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

public class Employee
{
    public string EmployeeNumber { get; set; }
    public string title { get; set; }
    public string Name { get; set; }

    public JProperty ToJProperty()
    {
        return new JProperty(EmployeeNumber,
            new JObject {
                { "title", title },
                { "Name", Name }
            });
    }
}

public class EmployeeRecords
{
    public List<Employee> Employees { get; set; }

    public JObject ToJObject()
    {
        var obj = new JObject();
        foreach (var employee in Employees)
        {
            obj.Add(employee.ToJProperty());
        }
        return new JObject {
            new JProperty("EmployeeRecords", obj)
        };
    }
}

class Test
{
    static void Main()
    {
        var records = new EmployeeRecords {
            Employees = new List<Employee> {
                new Employee {
                    EmployeeNumber = "12",
                    title = "Mr",
                    Name = "John"
                },
                new Employee {
                    EmployeeNumber = "35",
                    title = "Mr",
                    Name = "Json"
                },
            }
        };
        Console.WriteLine(records.ToJObject());
    }    
}

It may not be the simplest code (Ufuk's approach is great if you're happy to change your structuring), but it shows how customizable everything is.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194