0
0
CsharpHow-ToBeginner · 2 min read

C# How to Convert Dictionary to JSON String Easily

In C#, convert a dictionary to JSON by using JsonSerializer.Serialize(yourDictionary) from System.Text.Json namespace.
📋

Examples

Input{"apple": 1, "banana": 2}
Output{"apple":1,"banana":2}
Input{"name": "John", "age": 30}
Output{"name":"John","age":30}
Input{}
Output{}
🧠

How to Think About It

To convert a dictionary to JSON in C#, you use a built-in serializer that turns the dictionary's keys and values into a JSON string format. This is done by calling a method that reads the dictionary and outputs a string that looks like JSON, which can be used for data exchange or storage.
📐

Algorithm

1
Import the JSON serialization library.
2
Create or get the dictionary you want to convert.
3
Call the serialization method with the dictionary as input.
4
Store or print the resulting JSON string.
💻

Code

csharp
using System;
using System.Collections.Generic;
using System.Text.Json;

class Program
{
    static void Main()
    {
        var dict = new Dictionary<string, int> { {"apple", 1}, {"banana", 2} };
        string json = JsonSerializer.Serialize(dict);
        Console.WriteLine(json);
    }
}
Output
{"apple":1,"banana":2}
🔍

Dry Run

Let's trace converting a dictionary {"apple": 1, "banana": 2} to JSON string.

1

Create Dictionary

Dictionary contains keys 'apple' and 'banana' with values 1 and 2.

2

Serialize Dictionary

Call JsonSerializer.Serialize with the dictionary.

3

Output JSON

Resulting JSON string is '{"apple":1,"banana":2}'.

StepActionValue
1Dictionary{"apple":1,"banana":2}
2SerializeJson string generated
3Output{"apple":1,"banana":2}
💡

Why This Works

Step 1: Use System.Text.Json

The JsonSerializer class in System.Text.Json provides a simple way to convert objects like dictionaries into JSON strings.

Step 2: Serialize Dictionary

Calling Serialize() reads all keys and values in the dictionary and formats them as JSON key-value pairs.

Step 3: Get JSON String

The output is a string that represents the dictionary in JSON format, which can be printed or saved.

🔄

Alternative Approaches

Newtonsoft.Json (Json.NET)
csharp
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        var dict = new Dictionary<string, int> { {"apple", 1}, {"banana", 2} };
        string json = JsonConvert.SerializeObject(dict);
        Console.WriteLine(json);
    }
}
Newtonsoft.Json is a popular third-party library with more features but requires adding a package.
Manual String Building
csharp
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
        var dict = new Dictionary<string, int> { {"apple", 1}, {"banana", 2} };
        var sb = new StringBuilder();
        sb.Append("{");
        foreach (var kvp in dict)
        {
            sb.Append($"\"{kvp.Key}\":{kvp.Value},");
        }
        if (dict.Count > 0) sb.Length--;
        sb.Append("}");
        Console.WriteLine(sb.ToString());
    }
}
Manual building works but is error-prone and not recommended for complex data.

Complexity: O(n) time, O(n) space

Time Complexity

Serialization loops through each key-value pair once, so time grows linearly with dictionary size.

Space Complexity

The JSON string size grows with the number of entries, so space is proportional to dictionary size.

Which Approach is Fastest?

Using System.Text.Json is faster and more efficient than manual string building or older libraries.

ApproachTimeSpaceBest For
System.Text.JsonO(n)O(n)Built-in, fast, simple
Newtonsoft.JsonO(n)O(n)Feature-rich, widely used
Manual String BuildingO(n)O(n)Simple cases, no dependencies
💡
Use System.Text.Json.JsonSerializer.Serialize() for fast and easy dictionary to JSON conversion in C#.
⚠️
Forgetting to include using System.Text.Json; or trying to serialize without a proper serializer causes errors.