How to serialize an object using the JsonSerializer in C#

System.Text.Json, available since .NetCore 3.1, is the new JSON library for .NET. It focuses more on security, performance, and standards compliance than its predecessor, Newtonsoft.Json.

The JsonSerializer is a static class in the System.Text.Json namespace. It provides functionality for serializing objects to a JSON string and deserializing from a JSON string to objects.

The JsonSerializer has the serialize() method with multiple overloads, which is a highly performant method for serialization in .NET.

Syntax

public static string Serialize<TValue> (TValue inputValue, System.Text.Json.JsonSerializerOptions? options = default);

Input parameters

Parameter Description
inputValue The input object which we want to convert to a JSON string
options Serialization settings

This method serializes the provided object and returns a JSON string.

By default, the JSON string is minified. This means that all whitespace, indentation, and new-line characters are removed. You can configure all these settings by passing theJsonSerializerOptions object.

Code

We will use the JsonSerializer class present in the System.Text.Json namespace. This is built-in from .NET Core 3.0 and later versions.

However, in case you are on an older version of .NET, you can install the System.Text.Json NuGet package, which supports various older versions of .NET and .NET Core.

The following commands can be used to install this package using the PackageManager/dotnet CLI.

Install-Package System.Text.Json -Version 5.0.2
dotnet add package System.Text.Json --version 5.0.2

The code below converts the Employee object to a JSON string and displays the following output.

{"name":"Siddharth","salary":1000,"department":"IT"}
using System;
using System.Text.Json;
namespace JsonTest
{
class ObjectSerializer
{
static void Main(string[] args)
{
Employee employee = new Employee
{
name = "Siddharth",
salary = 1000,
department = "IT"
};
string jsonString = JsonSerializer.Serialize(employee);
Console.WriteLine(jsonString);
}
}
class Employee
{
public string name { get; set; }
public int salary { get; set; }
public string department { get; set; }
}
}

Free Resources