Write Json to a File JObject, JProperty C# code example

Write Json to a File JObject, JProperty C# code example

JObject and JProperty

In this article we will learn how to write json into a file using Newtonsoft JObject and JProperty. Latest Newtonsoft library can be obtained from NuGet Package or use command as given below on console. In this article we will be using two methods to write json into a file.

Install-Package Newtonsoft.Json -Version 12.0.3

Following name space needs to be imported:

using Newtonsoft.Json.Linq;

JObject, JProperty

JObject population = new JObject(
    new JProperty("Male", 10000),
    new JProperty("Female", 20000),
    new JProperty("Young", 15000)),
	new JProperty("Children", 25000)),
	new JProperty("Infant", 15000));

File.WriteAllText(@"c:\population.json", population.ToString());

JsonTextWriter

JObject population = new JObject(
    new JProperty("Male", 10000),
    new JProperty("Female", 20000),
    new JProperty("Young", 15000)),
	new JProperty("Children", 25000)),
	new JProperty("Infant", 15000));

// write JSON directly to a file
using (StreamWriter oFile = File.CreateText(@"c:\population.json"))
using (JsonTextWriter writer = new JsonTextWriter(oFile))
{
    population.WriteTo(writer);
}

Next >> Convert Json to Custom Collection Code example

Leave a Reply

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