// Create a new JsonTextWriter and a StreamWriter to write to a file using (var sw = new StreamWriter(@"C:\temp\output.json")) using (var jw = new JsonTextWriter(sw)) { // Start writing JSON data jw.WriteStartObject(); jw.WritePropertyName("name"); jw.WriteValue("John"); jw.WritePropertyName("age"); jw.WriteValue(30); jw.WriteEndObject(); }
// Create a new JsonTextWriter and a MemoryStream to write to a stream using (var ms = new MemoryStream()) using (var jw = new JsonTextWriter(new StreamWriter(ms))) { // Start writing JSON data jw.WriteStartObject(); jw.WritePropertyName("name"); jw.WriteValue("John"); jw.WritePropertyName("age"); jw.WriteValue(30); jw.WritePropertyName("address"); jw.WriteStartObject(); jw.WritePropertyName("street"); jw.WriteValue("Main St."); jw.WritePropertyName("city"); jw.WriteValue("New York"); jw.WriteEndObject(); jw.WriteEndObject(); // Get the JSON data as a byte array var json = ms.ToArray(); // Convert the JSON data to a string and write it to the console Console.WriteLine(Encoding.UTF8.GetString(json)); }In this example, we use a MemoryStream object instead of a file to write JSON data. We also write a more complex object that includes an embedded object (address). We get the JSON data as a byte array and convert it to a string before writing it to the console. Overall, the JsonTextWriter class is a powerful tool for writing JSON data in csharp. It is part of the Newtonsoft.Json NuGet package and is widely used in many applications and frameworks.