Generate Nested object with Json.NET’s JsonWriter

Been using Json.NET for the pass few months for projects that is related to JSON, a wonderful features provided is to allow you to Serialize your .Net objects to JSON format automatically.

string json = JsonConvert.SerializeObject(myObject);

For my case, my objects is shared between search results and detail page, search result required around 15 values where as the detail page have 50 values.

Using the JsonConvert.SerializeObject() method will make my search result’s JSON large in size, so i decided to use the manual way of generating the JSON via JsonWriter.

However, took me some time to generate a nested object JSON string.

  1. using (JsonWriter jsonWriter = new JsonTextWriter(sw))
  2. {
  3.     jsonWriter.WriteStartObject();
  4.     jsonWriter.WritePropertyName("model");
  5.     jsonWriter.WriteValue("Impreza");
  7.     jsonWriter.WritePropertyName("brand");
  8.     jsonWriter.WriteValue("Subaru");
  10.     jsonWriter.WritePropertyName("Engine");
  11.     jsonWriter.WriteStartObject();
  12.     jsonWriter.WritePropertyName("cc");
  13.     jsonWriter.WriteValue("2500");
  14.     jsonWriter.WritePropertyName("type");
  15.     jsonWriter.WriteValue("boxer");
  16.     jsonWriter.WriteEndObject();
  18.     jsonWriter.WriteEndObject();
  19. }
    "model": "Impreza",
    "brand": "Subaru",
    "Engine": {
        "cc": "2500",
        "type": "boxer"

Serializing/Deserializing Dictionary of objects with JSON.NET