C# – Serialize a dictionary to JSON

When you want to convert a dictionary to a JSON string, you can use the built-in JsonSerializer (from System.Text.Json) to serialize the dictionary. Here’s an example:

using System.Text.Json;

var dictionary = new Dictionary<int, Person>()
{
    [100] = new Person() { Name="Bob", Age=40},
    [101] = new Person() { Name="Teddy", Age=45}
};

var options = new JsonSerializerOptions() { WriteIndented = true };
var json = JsonSerializer.Serialize(dictionary, options);

Console.WriteLine(json);
Code language: C# (cs)

Note: This is passing in WriteIndented=true to pretty print the JSON string for readability.

This serializes the dictionary to a JSON string with the following format:

{
  "100": {
    "Name": "Bob",
    "Age": 40
  },
  "101": {
    "Name": "Teddy",
    "Age": 45
  }
}Code language: JSON / JSON with Comments (json)

I’ll show more examples for different scenarios below.

Serialize dictionary to JSON array

Dictionaries are serialized to a JSON object format by default. If you want use a JSON array format instead, the simplest option is to serialize a list of the dictionary’s key/value pairs. Here’s an example:

using System.Text.Json;
using System.Linq;

var dictionary = new Dictionary<int, string>()
{
    [100] = "Bob",
    [101] = "Teddy"
};

var json = JsonSerializer.Serialize(dictionary.AsEnumerable());

Console.WriteLine(json);
Code language: C# (cs)

Using AsEnumerable() on the dictionary returns an IEnumerable of KeyValuePair objects. This is then serialized as a JSON array and outputs the following:

[{"Key":100,"Value":"Bob"},{"Key":101,"Value":"Teddy"}]Code language: JSON / JSON with Comments (json)

I’d suggest using AsEnumerable() instead of ToList() in this scenario because it’s a memory-efficient generator method. System.Text.Json handles IEnumerable as expected.

Change the dictionary key casing

Dictionary keys are serialized as-is using the same casing they have in the dictionary. You can use the DictionaryKeyPolicy setting to change the casing of the keys. Here’s an example of making it so the dictionary keys are serialized using camel-casing:

using System.Text.Json;

var dictionary = new Dictionary<string, Person>()
{
    ["Chef"] = new Person() { Name = "Bob", Age = 40 },
    ["Foodie"] = new Person() { Name = "Teddy", Age = 45 }
};

var options = new JsonSerializerOptions() 
{ 
    WriteIndented = true,
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
};

var json = JsonSerializer.Serialize(dictionary, options);

Console.WriteLine(json);
Code language: C# (cs)

This outputs the following JSON. Notice that the keys (“Chef” and “Foodie”) are camel-cased (“chef” and “foodie”) in the JSON string:

{
  "chef": {
    "Name": "Bob",
    "Age": 40
  },
  "foodie": {
    "Name": "Teddy",
    "Age": 45
  }
}
Code language: JSON / JSON with Comments (json)

Also notice that the casing of the other properties (“Name” and “Age”) are unchanged. DictionaryKeyPolicy is specifically for controlling the casing of dictionary keys. You can change the property name casing with a separate option.

Serialize a dictionary with Newtonsoft

If you’re using Newtonsoft, you can serialize a dictionary with JsonConvert.SerializeObject(), like this:

using Newtonsoft.Json;

var dictionary = new Dictionary<int, Person>()
{
    [100] = new Person() { Name = "Bob", Age = 40 },
    [101] = new Person() { Name = "Teddy", Age = 45 }
};

var json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);

Console.WriteLine(json);
Code language: C# (cs)

This outputs the following JSON:

{
  "100": {
    "Name": "Bob",
    "Age": 40
  },
  "101": {
    "Name": "Teddy",
    "Age": 45
  }
}Code language: JSON / JSON with Comments (json)

If you want to serialize the dictionary to a JSON array instead, get the dictionary’s key/value pairs as a list by calling ToList(). Then pass this list into JsonConvert.SerializerObject(). Here’s an example:

using Newtonsoft.Json;
using System.Linq;

var dictionary = new Dictionary<int, string>()
{
    [100] = "Bob",
    [101] = "Teddy"
};

var json = JsonConvert.SerializeObject(dictionary.ToList());

Console.WriteLine(json);
Code language: C# (cs)

Note: Use ToList() when you’re using Newtonsoft. Don’t use AsEnumerable(), since Newtonsoft doesn’t serialize that to a JSON array.

This serializes the list of KeyValuePair objects as a JSON array. This outputs the following:

[{"Key":100,"Value":"Bob"},{"Key":101,"Value":"Teddy"}]Code language: JSON / JSON with Comments (json)

Leave a Comment