Create Json from Newtonsoft Anonymous type C#

Create Json from Newtonsoft Anonymous type C#

Ideally an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In context to a C# class, an anonymous type cannot have a field or a method only can have properties. In this article we will see how we can create json from Anonymous type step by step:

EmployDetail.css

public class EmployeeDetail
{
	public string employeeName { get; set; }
	public int empCode { get; set; }
	public IList<string> gender { get; set; }
}

Reference following in your main class:

using Newtonsoft.Json.Linq;

Implementation

List<EmployeeDetail> oEmployeeDetails = new List<EmployeeDetail>
{
    new EmployeeDetail
    {
        employeeName = "John",
        empCode = 1001,
        gender = new List<string>
        {
            "male",
            "female"
        }
    }
};


//Anonymous call
JObject oJobject = JObject.FromObject(new
{
    Department = new
    {
        departmentName="Account",
        role =
            from p in oEmployeeDetail
            orderby p.empCode
            select new
            {
                employeeName = p.employeeName,
                empCode = p.empCode,
                gender = p.gender
            }
    }
});

//get json

Console.WriteLine(oJobject.ToString());

Output

figure 1.0

Leave a Reply

Your email address will not be published.