Create JSON from Newtonsoft JToken FromObject C# code example

Create JSON from Newtonsoft JToken FromObject C# code example

FromObject

There are many ways to create json in C# by using various inbuilt or external libraries. Newtonsoft exposes JToken.FromObject, gives luxury to manipulate and create json. You can refer following solutions which shows different ways to create json in C# .Net:

Different ways

EmplyeeDetails.css

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

Step 2: Import Newtonsoft json library through NuGet Package Manager and put following reference in your project:

using Newtonsoft.Json.Linq

Code example

private void btnJtodken_Click(object sender, RibbonControlEventArgs e)
{
	
	//declare a list to hold multiple employees
	List<EmployeeDetails> oListEmployeeDetailses=new List<EmployeeDetails>();
	
	//Loop to generate multiple employee records 
	for (int i = 1000; i <= 1010; i++)
	{
		//Add emplyee details
		EmployeeDetails oEmployeeDetails = new EmployeeDetails();
		oEmployeeDetails.empCode = i;
		oEmployeeDetails.employeeName = "VBAOVERALL - " + i.ToString();

		//Create a list
		IList<string> genderList=new List<string>();
		genderList.Add("Male");
		genderList.Add("Female");
		//push list
		oEmployeeDetails.gender = genderList;                

		//Populate collection
		oListEmployeeDetailses.Add(oEmployeeDetails);
	}
	
	//Create JArray to serialize object into json
	JArray oemployeeJObject = (JArray) JToken.FromObject(oListEmployeeDetailses);

	//Grab the json
	Console.WriteLine(oemployeeJObject.ToString());
}

Output

figure 1.0

Next >> Json to Value converter C# code example

Leave a Reply

Your email address will not be published.