This post will discuss how to get formatted JSON in C#.

By default, JSON is serialized without any white space. To improve readability, it is often desired to get an indented JSON. There are several options to achieve that in C#:

1. Using JsonSerializer.Serialize() method

For .NET versions 4.7.2 and above, you can use the JsonSerializer.Serialize() method from System.Text.Json namespace to format a JSON string. It accepts the JsonSerializerOptions class to control the conversion behavior. The WriteIndented property indicates whether JSON should use pretty printing. To pretty-print the JSON, set the WriteIndented option to true, as the following example illustrates.

Download Code

Output:

[
  {
    "Name": "Chris",
    "Age": 25
  },
  {
    "Name": "Jennifer",
    "Age": 20
  }
]

 
To prettify a JSON string, you can deserialize it first using the JsonSerializer.Deserialize() method.

Download Code

Output:

[
  {
    "Name": "Chris",
    "Age": 25
  },
  {
    "Name": "Jennifer",
    "Age": 20
  }
]

2. Using JsonConvert.SerializeObject() method

Another option is to use the JsonConvert.SerializeObject() method (available in Newtonsoft.Json namespace) from the Json.NET library to serialize an object to a formatted JSON string. The following code example demonstrates calling this method:

Download Code

Output:

[
  {
    "Name": "Chris",
    "Age": 25
  },
  {
    "Name": "Jennifer",
    "Age": 20
  }
]

 
The following code converts an existing JSON string to a formatted JSON string, without deserializing it into a typed object.

Download Code

Output:

[
  {
    "Name": "Chris",
    "Age": 25
  },
  {
    "Name": "Jennifer",
    "Age": 20
  }
]

3. Using JToken.FromObject() method

Alternatively, you can use the JToken.FromObject() method (available in Newtonsoft.Json.Linq namespace) from the Json.NET library that returns a JToken with the value of the specified object. Then invoke the ToString() on this token, which returns the indented JSON.

Download Code

Output:

[
  {
    "Name": "Chris",
    "Age": 25
  },
  {
    "Name": "Jennifer",
    "Age": 20
  }
]

 
To prettify an existing JSON without deserializing it into a .NET type, you can do like:

Download Code

Output:

[
  {
    "Name": "Chris",
    "Age": 25
  },
  {
    "Name": "Jennifer",
    "Age": 20
  }
]

That’s all about getting formatted JSON in C#.