C# How to Convert Dictionary to JSON String Easily
JsonSerializer.Serialize(yourDictionary) from System.Text.Json namespace.Examples
How to Think About It
Algorithm
Code
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); } }
Dry Run
Let's trace converting a dictionary {"apple": 1, "banana": 2} to JSON string.
Create Dictionary
Dictionary contains keys 'apple' and 'banana' with values 1 and 2.
Serialize Dictionary
Call JsonSerializer.Serialize with the dictionary.
Output JSON
Resulting JSON string is '{"apple":1,"banana":2}'.
| Step | Action | Value |
|---|---|---|
| 1 | Dictionary | {"apple":1,"banana":2} |
| 2 | Serialize | Json string generated |
| 3 | Output | {"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
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); } }
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()); } }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| System.Text.Json | O(n) | O(n) | Built-in, fast, simple |
| Newtonsoft.Json | O(n) | O(n) | Feature-rich, widely used |
| Manual String Building | O(n) | O(n) | Simple cases, no dependencies |
System.Text.Json.JsonSerializer.Serialize() for fast and easy dictionary to JSON conversion in C#.using System.Text.Json; or trying to serialize without a proper serializer causes errors.