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.
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.
See more on this question at Stackoverflow