C#
.NET
JSON
CodeFormatting
ProgrammingTips

How do I get formatted JSON in .NET using C?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

To format JSON in .NET using C#, you'll primarily work with classes available in the System.Text.Json namespace, which was introduced in .NET Core 3.0 and later. Alternatives exist, such as using Newtonsoft.Json, also known as Json.NET, which is favored by many for its rich features despite being an external library. This article discusses how to utilize both of these libraries for formatting JSON in .NET.

Using System.Text.Json

System.Text.Json provides built-in functionality to serialize and deserialize JSON with ease. Formatting JSON in this context refers to serializing an object with proper indentation for improved readability.

Installation & Setup

System.Text.Json is included in .NET Core 3.0 and later; hence, no additional packages are needed.

Example of Formatting JSON

Here is how you can serialize an object to a formatted JSON string using System.Text.Json.

csharp
1using System;
2using System.Text.Json;
3using System.Text.Json.Serialization;
4
5public class Person
6{
7    public string FirstName { get; set; }
8    public string LastName { get; set; }
9    public int Age { get; set; }
10}
11
12class Program
13{
14    static void Main()
15    {
16        var person = new Person
17        {
18            FirstName = "John",
19            LastName = "Doe",
20            Age = 30
21        };
22
23        var jsonOptions = new JsonSerializerOptions
24        {
25            WriteIndented = true
26        };
27
28        string formattedJson = JsonSerializer.Serialize(person, jsonOptions);
29        Console.WriteLine(formattedJson);
30    }
31}

Explanation

  • JsonSerializerOptions: This allows customization of the JSON serialization process. Here, setting WriteIndented = true enables formatted (indented) JSON output.
  • Output: The formatted JSON string will be indent-based and human-readable.

Using Newtonsoft.Json

Newtonsoft.Json (Json.NET) is an alternative to System.Text.Json, providing extensive features and customizable options for JSON handling.

Installation & Setup

To use Newtonsoft.Json, you need to add the NuGet package to your project:

bash
dotnet add package Newtonsoft.Json

Example of Formatting JSON

Below is how you can achieve formatted JSON using Newtonsoft.Json.

csharp
1using System;
2using Newtonsoft.Json;
3
4public class Person
5{
6    public string FirstName { get; set; }
7    public string LastName { get; set; }
8    public int Age { get; set; }
9}
10
11class Program
12{
13    static void Main()
14    {
15        var person = new Person
16        {
17            FirstName = "Jane",
18            LastName = "Doe",
19            Age = 25
20        };
21
22        string formattedJson = JsonConvert.SerializeObject(person, Formatting.Indented);
23        Console.WriteLine(formattedJson);
24    }
25}

Explanation

  • JsonConvert.SerializeObject: This is the serialization method in Newtonsoft.Json.
  • Formatting.Indented: This parameter configures the JSON to be output with indentation.

Key Differences Between System.Text.Json and Newtonsoft.Json

FeatureSystem.Text.JsonNewtonsoft.Json
PerformanceHigh performance due to Span and UTF-8 integrationRelatively lower performance compared to System.Text.Json
Built-in SupportPart of .NET Core 3.0 and laterExternal library, needs installation
IndentationSupported via JsonSerializerOptions WriteIndented = trueSupported via Formatting.Indented
FlexibilityLess flexible with serialization and deserializationVery flexible with extensive options
LINQ supportNo direct supportDirect support for querying with LINQ

Conclusion

Both System.Text.Json and Newtonsoft.Json provide robust options to serialize and format JSON in a human-readable form. While System.Text.Json offers improved performance and is part of the .NET framework, Newtonsoft.Json provides extensive features and flexibility, making it a popular choice among developers. Choose the one that best fits your project’s requirements.


Course illustration
Course illustration

All Rights Reserved.