using (StreamWriter file = File.CreateText(@"C:\temp\example.json")) using (JsonWriter writer = new JsonTextWriter(file)) { writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("John Doe"); writer.WritePropertyName("age"); writer.WriteValue(30); writer.WritePropertyName("isMarried"); writer.WriteValue(true); writer.WriteEndObject(); }
using (StringWriter sw = new StringWriter()) using (JsonWriter writer = new JsonTextWriter(sw)) { writer.WriteStartArray(); writer.WriteValue(1); writer.WriteValue("two"); writer.WriteValue(true); writer.WriteEndArray(); string json = sw.ToString(); }This example creates a JSON array with three values (a number, a string and a boolean) and writes it to a StringWriter. The resulting JSON string is then obtained from the StringWriter. Overall, JsonWriter is a useful class in the Newtonsoft.Json library for writing JSON data in a structured way.