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:


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;


List<EmployeeDetail> oEmployeeDetails = new List<EmployeeDetail>
    new EmployeeDetail
        employeeName = "John",
        empCode = 1001,
        gender = new List<string>

//Anonymous call
JObject oJobject = JObject.FromObject(new
    Department = new
        role =
            from p in oEmployeeDetail
            orderby p.empCode
            select new
                employeeName = p.employeeName,
                empCode = p.empCode,
                gender = p.gender

//get json



figure 1.0

Leave a Reply

Your email address will not be published. Required fields are marked *