Exploring Enhanced Serialization in .NET 9 with System.Text.Json
Tags: dotnet, aspnet, csharp, coding
Published: 2024-03-16 03:08:03

.NET 9’s System.Text.Json introduces improved JSON serialization with customizable indentation using JsonSerializerOptions. A new singleton, JsonSerializerDefaults, streamlines web-based serialization with default options, enhancing the overall handling of JSON data in .NET applications.

## Introduction

Serialization plays a pivotal role in contemporary software development, especially when handling data interchange formats such as JSON. In the dynamic realm of .NET, version 9 brings significant enhancements to the System.Text.Json namespace, providing advanced choices for JSON serialization. Noteworthy additions include features that empower developers to manage indentation with precision and a user-friendly singleton designed for streamlined web-based serialization.

## Customizing Indentation with JsonSerializerOptions

One of the key enhancements in .NET 9 is the ability to fine-tune the indentation of JSON output. This is particularly useful for improving the human readability of the generated JSON files. The JsonSerializerOptions class now includes properties that allow developers to customize both the indentation character and size.

## Example in .Net

Let’s take a look at a simple example in C#:

    var options = new JsonSerializerOptions
    {
        WriteIndented = true,
        IndentCharacter = '\t',
        IndentSize = 2,
    };
    
    string json = JsonSerializer.Serialize(
        new { Value = 1 },
        options
    );
    Console.WriteLine(json);

In the given illustration, we instantiate a JsonSerializerOptions object and configure the WriteIndented property to be true. This guarantees that the resulting JSON will be presented in a structured format with appropriate indentation. The IndentCharacter property facilitates the selection of the indentation character, while the IndentSize property dictates the quantity of spaces or tabs allocated for each tier of indentation.

## Output

The output of the above code snippet would be:

    {
            "Value": 1
    }

As demonstrated, the JSON now includes proper indentation, making it more readable and developer-friendly.

## Web Defaults Serialization Singleton

.NET 9 also introduces a new singleton, JsonSerializerDefaults, that simplifies the process of serializing using web defaults. This singleton provides default options for serialization in a web context, ensuring a consistent and optimized approach.

## Example in .Net

Here’s an example of using JsonSerializerDefaults for web-based serialization:

    string json = JsonSerializer.Serialize(
        new { Value = 1 },
        JsonSerializerDefaults.Web
    );
    
    Console.WriteLine(json);

In this example, we use the JsonSerializerDefaults.Web singleton to serialize the object with default web-based options. This is particularly handy in scenarios where standard web conventions need to be followed.

## Conclusion

With the enhancements in .NET 9’s System.Text.Json namespace, developers now have more control over the serialization process. The ability to customize indentation options and the introduction of the JsonSerializerDefaults singleton for web defaults make it easier to tailor the serialization process to specific requirements. These improvements not only enhance developer experience but also contribute to the overall readability and consistency of JSON output in .NET applications. As developers embrace these new features, the serialization capabilities of .NET 9 continue to evolve, offering a more refined and versatile experience for handling JSON data.

> Congratulations on making it this far without your keyboard catching fire! 🔥 
> Now, if you've managed to dodge the bugs and not ctrl+alt+delete your screen, show some love with a heart or spill your thoughts in the comments!! 🖐️🤓

Now, to keep the tech party going, follow me on these channels:

[C# Publication](https://medium.com/c-sharp-progarmming) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh-532284a2/) |  [Instagram](https://www.instagram.com/sukhpindersukh/) | [Twitter](https://twitter.com/sukhsukhpinder) |  [Dev.to](https://dev.to/ssukhpinder)

![Buymeacoffee](https://cdn-images-1.medium.com/max/2000/1*Dpw8-hNGI2fDmosV4E8DVQ.png)

### More Articles
[**.NET Strategies for Integrating Decorators**](https://medium.com/c-sharp-progarmming/net-strategies-for-integrating-decorators-90369f04b438)
[**Get Started: Building Your Initial .NET Aspire App**](https://medium.com/c-sharp-progarmming/get-started-building-your-initial-net-aspire-app-cf420f0dff2f)
[**Unlocking OpenAI Integration with .NET 8**](https://medium.com/c-sharp-progarmming/unlocking-openai-integration-with-net-8-be2755b3ac94)
[**Unlock Your Future: Get Certified in C# for Free Now**](https://medium.com/c-sharp-progarmming/unlock-your-future-get-certified-in-c-for-free-now-64abd67687ed)
[**Exploring Different Methods to Fetch the Application’s Path**](https://medium.com/c-sharp-progarmming/exploring-different-methods-to-fetch-the-applications-path-d7d8cbf5608f)
[**Best Practices for Base Constructor Calls in C#**](https://medium.com/c-sharp-progarmming/best-practices-for-base-constructor-calls-in-c-284da2cda473)