This post will discuss how to write to JavaScript Object Notation (JSON) file in C#.

1. Using JsonSerializer.Serialize() method

The recommended solution to serialize and deserialize JSON in .NET 4.7.2 and above, is using the System.Text.Json namespace. You can use the JsonSerializer class with custom types to serialize from and deserialize into. For serialization and deserialization, you also need to include the System.Text.Json.Serialization namespace.

The following solution shows the use of the JsonSerializer.Serialize() method for converting an object to a JSON string. It then writes the JSON string to a file using the File.WriteAllText() method.

Download Code

Customers.json:

[{"Name":"Jason","Age":25},{"Name":"Nikki","Age":20}]

 
To pretty-print the JSON string, you can set the JsonSerializerOptions.WriteIndented to true. However, formatting the JSON might have a negative impact on performance.

Download Code

Customers.json:

[
  {
    "Name": "Jason",
    "Age": 25
  },
  {
    "Name": "Nikki",
    "Age": 20
  }
]

2. Using JsonConvert.SerializeObject() method

Alternatively, you can use the Json.NET library to serialize to and deserialize from JSON. The Newtonsoft.Json namespace provides the JsonConvert class that provides several methods for converting between .NET types and JSON types.

The following example serializes an object to JSON using the SerializeObject() method and then outputs the JSON string to a file using the File.WriteAllText() method.

Download Code

Customers.json:

[{"Name":"Jason","Age":25},{"Name":"Nikki","Age":20}]

 
To format the JSON for readability purpose, you can pass the Formatting.Indented option to the JsonConvert.SerializeObject() method.

Download Code

Customers.json:

[
  {
    "Name": "Jason",
    "Age": 25
  },
  {
    "Name": "Nikki",
    "Age": 20
  }
]

3. Using JavaScriptSerializer.Serialize() method

Finally, for AJAX applications, you can use the JavaScriptSerializer class for serialization and deserialization. To serialize an object to a JSON string, you can use its Serialize() method. The following example illustrates.

Download Code

Customers.json:

[{"Name":"Jason","Age":25},{"Name":"Nikki","Age":20}]

That’s all about writing to JavaScript Object Notation (JSON) file in C#.