Json using JTokenWriter C# example

Json using JTokenWriter C# example

JTokenWriter

There are different ways to create a json using C# depends on the right fight for the developer. In my previous article I have explained how to create json using StringBuilder here. In this article we will see how we can create json using JTokenWriter object of Newtonsoft. Add Newtonsoft open source package in your solution and add the following reference in your code to access JTokenWriter:

Import

using Newtonsoft.Json.Linq

figure 1.0

Code example

private void JtodkenExample_Click(object sender, RibbonControlEventArgs e)
{
	//declare jtokenwriter reference
	JTokenWriter jWriter= new JTokenWriter();
	
	//adding json elements
	//refers to {
	jWriter.WriteStartObject();
	//adding property name
	jWriter.WritePropertyName("employee");
	//adding property value
	jWriter.WriteValue("VBAOVERALL");
	//adding property name
	jWriter.WritePropertyName("city");
	//adding property value
	jWriter.WriteValue("pune");
	//adding Array property name
	jWriter.WritePropertyName("gender");
	//add array object refers [
	jWriter.WriteStartArray();
	//adding values
	jWriter.WriteValue("male");
	//adding values
	jWriter.WriteValue("female");
	//end of array refers ]
	jWriter.WriteEndArray();
	//end object refers }
	jWriter.WriteEndObject();

	//create jobject and take the token into
	JObject oJObject = (JObject) jWriter.Token;

	//write the json
	Console.WriteLine(oJObject.ToString());
}

Next >> JToken CreateReader vs CreateWriter C# example

Leave a Reply

Your email address will not be published.