JsonWriter writer = new JsonTextWriter(new StringWriter()); writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("John Doe"); writer.WritePropertyName("age"); writer.WriteValue(30); writer.WriteEndObject(); string json = writer.ToString();
JsonWriter writer = new JsonTextWriter(new StringWriter()); writer.WriteStartObject(); writer.WritePropertyName("person"); writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("John Doe"); writer.WritePropertyName("age"); writer.WriteValue(30); writer.WriteEndObject(); writer.WriteEndObject(); string json = writer.ToString();This example demonstrates how to add nested objects to the JSON output. We start by creating a new object and then call WritePropertyName to add a property with the name "person". We then call WriteStartObject to add a nested object and add properties to it using the WritePropertyName and WriteValue methods. Finally, we call WriteEndObject to close both nested objects and retrieve the JSON output as a string. Overall, the JsonWriter's AddObject method is a useful tool for dynamically generating JSON output in C#. It is a part of the Newtonsoft.Json package, which is widely used and has many other useful features for working with JSON data.