Search code examples
c#jsonserializationjson.netjsonserializer

how to write Custom JSon serializer in C#


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.


Solution

  • 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;
    }