JavaScript Object Notation (JSON) is widely used for storing, transmitting, and communicating data across different systems and applications. Its simple syntax and ability to represent complex data structures make it an ideal choice for web services and APIs.

To facilitate the conversion of data to JSON format, C# offers various serialization approaches through popular libraries such as System.Text.Json and Newtonsoft.Json. In this article, we will discuss some of these techniques that we can use to serialize a list to JSON in C#.

At the end of the article, we will perform benchmark tests to evaluate the performance and memory allocations of the various methods discussed.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Prepare the Environment

To begin, let’s prepare our environment by creating the list object that we will use in this article.

First, let’s define a Club class:

public class Club
{
    public string Name { get; set; } = string.Empty;
    public int YearFounded { get; set; }
    public string Country { get; set; } = string.Empty;
    public string NumberOfPlayers { get; set; } = string.Empty;
    public string League { get; set; } = string.Empty;
    public bool HasAStadium { get; set; }
}

Next, let’s create a List<Club> object:

List<Club> _englishClubs = new()
{
    new Club
    {
        Name = "Arsenal",
        YearFounded = 1886,
        Country = "England",
        NumberOfPlayers = "26",
    },
    new Club
    {
        Name = "Manchester City",
        YearFounded = 1880,
        Country = "England",
        NumberOfPlayers = "25",
    },
    new Club
    {
        Name = "Sunderland",
        YearFounded = 1879,
        Country = "England",
        NumberOfPlayers = "30",
    }
 };

We will use this list as the input data for all the serialization methods in this article.

Serialize a List to JSON With System.Text.Json

The System.Text.Json namespace in .NET provides certain functionalities that we can use to work with JSON data.

To start using these functionalities to serialize a list to JSON in C#, let’s first define a SerializeListToJsonWithSystemTextJson class and a _clubList variable:

public class SerializeListToJsonWithSystemTextJson
{
    private readonly List<Club> _clubList;

    public SerializeListToJsonWithSystemTextJson(List<Club> clubList)
    {
        _clubList = clubList;
    }
}

Here, we define a class that will contain all the methods that utilize the System.Text.Json library. Next, we define a private readonly variable that points to the list that we want to serialize to JSON.

We then define a constructor that sets the value of _clubList to clubList. When we want to invoke the methods defined in this class, we can use this constructor to set the value of _clubList.

Alright, we can now discuss different ways that we can serialize a list to JSON in C# using the System.Text.Json namespace.

Serialize a List to JSON With the Serialize() Method

Now, let’s take a closer look at how we can use the Serialize() method from the System.Text.Json namespace to convert a list into a JSON string in C#.

First, let’s define a SerializeMethod() method:

public string SerializeMethod()
{
    return JsonSerializer.Serialize(_clubList);
}

In this method, we call the Serialize() method from the JsonSerializer class, passing in the List<T> object that we want to serialize as a parameter.

This method returns a minified (no indentation, whitespaces, and newline characters) string:

[{"Name":"Arsenal","YearFounded":1886,"Country":"England","NumberOfPlayers":"26"},
{"Name":"Manchester City","YearFounded":1880,"Country":"England","NumberOfPlayers":"25"},
{"Name":"Sunderland","YearFounded":1879,"Country":"England","NumberOfPlayers":"30"}]

This is the output string we desire and we can use it in this form to store data in a file or send information over a network to another application. However, it is not easily readable and the property names are not in the recommended JSON format (camelcase). Please note, in the code sample, we broke the string into several lines to enhance readability. 

To address these issues, let’s define an instance of the JsonSerializerOptions class:

private readonly JsonSerializerOptions _options = new()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true,
};

Here, we create an instance named _options and set two properties. First, we set the PropertyNamingPolicy property to JsonNamingPolicy.CamelCase. With this, when we serialize our list to JSON, it automatically converts the property names to camelcase.

Next, we set the WriteIndented property to true. When we utilize this instance for serializing our list to JSON, we ensure that it indents the resulting JSON string for better readability.

When we pass this _options variable to our SerializeMethod() and invoke it, we get:

[
  {
    "name": "Arsenal",
    "yearFounded": 1886,
    "country": "England",
    "numberOfPlayers": "26"
  },
  {
    "name": "Manchester City",
    "yearFounded": 1880,
    "country": "England",
    "numberOfPlayers": "25"
  },
  {
    "name": "Sunderland",
    "yearFounded": 1879,
    "country": "England",
    "numberOfPlayers": "30"
  }
]

As we can see, by using this instance, we can ensure that the returned JSON string is readable and follows the recommended format for property names. 

It is important to note that, when we use indentation in a large JSON file, it can improve readability, especially for nested objects or arrays. However, it can also increase the file size and make transmission over a network less efficient. Therefore, we should balance readability and file size when deciding whether to use indentation in a JSON file.

Serialize a List to JSON With the SerializeToUtf8Bytes() Method

Alternatively, we can use the SerializeToUtf8Bytes() method to serialize a C# list to JSON:

public string SerializeToUtf8BytesMethod()
{
    var result = JsonSerializer.SerializeToUtf8Bytes(_clubList, _options);

    return System.Text.Encoding.UTF8.GetString(result);
}

First, we invoke the JsonSerializer.SerializeToUtf8Bytes() method, passing in two arguments. The first argument is the List object _clubList and the second argument is _options, an instance of the JsonSerializerOptions class created earlier in this article. We use these options to control the formatting of the resulting JSON string, such as ensuring it is readable and that property names are in camelcase.

Once the serialization is complete, we obtain the resulting byte array and convert it to a string using the System.Text.Encoding.UTF8.GetString() method. Here, we pass in the byte array as an argument and the method returns a string in UTF-8 encoding.

Serialize a List to JSON With Newtonsoft.Json

So far, we’ve seen how to serialize a list to JSON using the native System.Text.Json library. But wait – there’s more. Let’s look at some other techniques that we can apply to convert a list to JSON in C# using the Newtonsoft.Json library.

To begin, let’s first define a SerializeListToJsonWithNewtonsoftJson class and a _clubList variable:

public class SerializeListToJsonWithNewtonsoftJson
{
    private readonly List<Club> _clubList;

    public SerializeListToJsonWithNewtonsoftJson(List<Club> clubList)
    {
        _clubList = clubList;
    }
}

Here, we create a class that will contain all the methods that utilize the Newtonsoft.Json library. We then define a private readonly variable that points to the list that we want to serialize to JSON.

After that, we define a constructor that sets the value of _clubList to clubList. We can use this constructor to set the value of _clubList when we want to call the methods defined in this class.

Next, to ensure that our methods return the JSON string in a readable format and that the property names are in camelcase by defining an instance of the JsonSerializerSettings class:

private readonly JsonSerializerSettings _settings = new()
{
    Formatting = Formatting.Indented,
    ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() },
};

In this instance, we initialize two settings. First, we set the Formatting property to Formatting.Indented. Setting this causes the returned JSON string to be indented for improved readability.

Then, we set the ContractResolver property to an instance of the DefaultContractResolver class. With this, when we serialize our list to JSON, it automatically converts the property names to camelcase. Here, we set the NamingStrategy property of the DefaultContractResolver to an instance of CamelCaseNamingStrategy. We do this to convert property names to camelcase during serialization.

Now, let’s explore the various methods that we can use to serialize a list to JSON using this library.

Serialize a List to JSON With the JsonConvert.SerializeObject() Method

With that, let’s explore how we can use the JsonConvert.SerializeObject() method to serialize a list to JSON.

First, let’s define a SerializeObjectMethod() method:

public string SerializeObjectMethod()
{
    return JsonConvert.SerializeObject(_clubList, _settings);
}

Here, we invoke the JsonConvert.SerializeObject() method, and pass in two parameters. The first parameter is the list object we want to serialize, and the second parameter is the instance of the JsonSerializerSettings class we created.

Serialize a List to JSON With the JsonSerializer Class

We’re not done yet. Let’s discuss how we can use the JsonSerializer class to convert a List<T> object to JSON:

public string JsonSerializerClass()
{
    var serializer = JsonSerializer.Create(_settings);
    var stringBuilder = new StringBuilder();
    using (var writer = new JsonTextWriter(new StringWriter(stringBuilder)))
    {
        serializer.Serialize(writer, _clubList);
    }

    return stringBuilder.ToString();
}

In the JsonSerializerClass() method, we create an instance of the JsonSerializer class by passing in our _settings object as an argument. We will use this instance to serialize our list to JSON.

Next, we create a new StringBuilder object that will store our JSON string. Then we use a JsonTextWriter instance to write our serialized JSON string to the StringBuilder.

Within the using statement, we pass in the JsonTextWriter instance and our list object _clubList as arguments to the serializer.Serialize() method and invoke it. This method serializes our _clubList to a JSON string, which we write to the StringBuilder.

Finally, we return the JSON string from the StringBuilder by calling the ToString() method.

What’s the Fastest Way to Serialize a List in C#?

With all our methods ready, let’s use the BenchmarkDotNet library to measure the time performance and memory allocation for each method. To learn more about how this library works, please visit Introduction to Benchmarking C# Projects.

To see more details of the benchmark implementation for these methods, please visit our repository.

Once we run the benchmark on a list of 10,000 Club objects, we can inspect our results on the console:

|                     Method |     Mean |    Error |   StdDev | Allocated |
|--------------------------- |---------:|---------:|---------:|----------:|
|            SerializeMethod | 16.42 ms | 0.359 ms | 1.047 ms |    3.7 MB |
| SerializeToUtf8BytesMethod | 17.82 ms | 0.351 ms | 0.456 ms |   5.48 MB |
|        JsonSerializerClass | 25.07 ms | 0.293 ms | 0.245 ms |   4.79 MB |
|      SerializeObjectMethod | 25.52 ms | 0.507 ms | 1.092 ms |   4.79 MB |

Based on the benchmark test results, the fastest way we can serialize a List<T> instance to JSON in C# is by invoking the SerializeMethod() method. This method also utilizes the least amount of memory among all the tested methods.

The SerializeToUtf8BytesMethod() method is slightly slower and allocates more memory than the SerializeMethod() method.

The JsonSerializerClass() method and the SerializeObjectMethod() method are both slower than the System.Text.Json-based methods. However, they both allocate the same amount of memory.

In general, it is evident that when we want to serialize a list to JSON in C#, the most optimal option is to utilize the SerializeMethod() method.

Conclusion

Let’s recap, JSON serialization is essential when we want to transfer data between our applications. C# has two popular libraries, System.Text.Json and Newtonsoft.Json, that we can use to serialize a list to JSON format.

In this article, we explored different ways of using these libraries to serialize a list to JSON in C#. We also discussed techniques to optimize code and generate easily readable JSON strings with recommended property name formats. Finally, we performed benchmark tests to compare the performance and memory usage of the methods and concluded that the Serialize() method from the System.Text.Json library is the optimal choice for serializing a list to JSON in C#.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!