JsonWriter writer = new JsonTextWriter(new StringWriter()); writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("John"); writer.WritePropertyName("age"); writer.WriteValue(30); writer.WriteEndObject(); Console.WriteLine(writer.ToString());
JsonWriter writer = new JsonTextWriter(new StringWriter()); writer.WriteStartObject(); writer.WritePropertyName("person"); writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("Jane"); writer.WritePropertyName("age"); writer.WriteValue(25); writer.WriteEndObject(); writer.WriteEndObject(); Console.WriteLine(writer.ToString());This example is similar to the first one, but instead of adding simple values, we add a nested JSON object with the key "person". We start the object with WriteStartObject, then use the AddProperty method to add two properties to it: "name" with the value "Jane", and "age" with the value 25. Finally, we end both objects and print the result to the console. This example also uses the Newtonsoft.Json package.