JToken CreateReader and CreateWriter C# code example

JToken CreateReader and CreateWriter C# code example

JToken

In this article we will see how we can manipulate json using CreateReader and CreateWriter methods of JToken object of Newtonsoft library.

CreateReader

//Use JObject and populate the json
JObject oJsonObject = new JObject
{
    { "Employee", "VBAOVERALL" },
    { "Salary", 12000 },
    {
        "Gender", new JArray
        {
            "Male",
            "Female"
        }
    }
};


//Instantiate CreateReader
JsonReader reader = oJsonObject.CreateReader();

//Loop through each
while (reader.Read())
{
    Console.Write(reader.TokenType);
    if (reader.Value != null)
    {
        Console.Write(" - " + reader.Value);
    }

    Console.WriteLine();
}

Output

StartObject
PropertyName – Employee
String – VBAOVERALL
PropertyName – Salary
Integer – 12000
PropertyName – Gender
StartArray
String – Male
String – Female
EndArray
EndObject

CreateWriter

JObject oJobject = new JObject
{
    { "SiteName", "VBAOVERALL.COM" },
    { "Grade", "Manager" }
};

JsonWriter writer = oJobject.CreateWriter();
writer.WritePropertyName("Gender");
writer.WriteStartArray();
writer.WriteValue("Male");
writer.WriteValue("Female");
writer.WriteEndArray();

Console.WriteLine(oJobject.ToString());

Output

{
	"SiteName": "VBAOVERALL.COM",
	"Grade":  "Manager",
	"Gender": [
		"Male",
		"Female"
	]
}

Next >> Function Wizard in Excel with VBA code example

Leave a Reply

Your email address will not be published.