var jsonString = @"{ 'Name': 'John', 'Age': 30, 'Address': { 'City': 'New York', 'State': 'NY' } }"; using (var stringReader = new StringReader(jsonString)) using (var jsonReader = new JsonTextReader(stringReader)) using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { while (jsonReader.Read()) { if (jsonReader.TokenType == JsonToken.PropertyName && (string)jsonReader.Value == "Address") { jsonWriter.WritePropertyName("Address"); jsonWriter.WriteStartObject(); while (jsonReader.Read()) { if (jsonReader.TokenType == JsonToken.EndObject) { jsonWriter.WriteEndObject(); break; } jsonWriter.WriteToken(jsonReader); } } else { jsonWriter.WriteToken(jsonReader); } } var result = stringWriter.ToString(); }
var jsonObject = new JObject( new JProperty("Name", "John"), new JProperty("Age", 30), new JProperty("Address", new JObject( new JProperty("City", "New York"), new JProperty("State", "NY") )) ); using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { jsonObject.WriteTo(jsonWriter); jsonWriter.WriteEndObject(); var result = stringWriter.ToString(); }This example demonstrates the usage of WriteEndObject method to write the end of a JSON object created using JObject class from the Newtonsoft.Json package library.