C# How to Convert JSON to Dictionary Easily
JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString) from System.Text.Json to convert a JSON string to a dictionary in C#.Examples
How to Think About It
Algorithm
Code
using System; using System.Collections.Generic; using System.Text.Json; class Program { static void Main() { string jsonString = "{\"name\":\"John\",\"age\":30}"; var dictionary = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString); foreach (var kvp in dictionary) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } } }
Dry Run
Let's trace the example JSON '{"name":"John","age":30}' through the code
Input JSON string
{"name":"John","age":30}
Deserialize JSON to dictionary
Dictionary
Print dictionary contents
Output lines: 'name: John' and 'age: 30'
| Key | Value |
|---|---|
| name | John |
| age | 30 |
Why This Works
Step 1: Deserialize JSON string
The JsonSerializer.Deserialize method reads the JSON string and converts it into a dictionary object with keys and values.
Step 2: Dictionary stores key-value pairs
Each JSON key becomes a dictionary key, and the JSON value becomes the dictionary value.
Step 3: Use dictionary in code
You can access dictionary values by their keys just like any other dictionary in C#.
Alternative Approaches
using System; using System.Collections.Generic; using Newtonsoft.Json; class Program { static void Main() { string jsonString = "{\"name\":\"John\",\"age\":30}"; var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString); foreach (var kvp in dictionary) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } } }
using System; using System.Collections.Generic; using System.Text.Json; class Program { static void Main() { string jsonString = "{\"name\":\"John\",\"age\":\"30\"}"; var dictionary = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonString); foreach (var kvp in dictionary) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } } }
Complexity: O(n) time, O(n) space
Time Complexity
Deserialization reads each character in the JSON string once, so time grows linearly with input size.
Space Complexity
The dictionary stores all key-value pairs, so space grows linearly with the number of entries.
Which Approach is Fastest?
Using System.Text.Json is faster and uses less memory than Newtonsoft.Json, but Newtonsoft.Json offers more features.
| Approach | Time | Space | Best For |
|---|---|---|---|
| System.Text.Json | O(n) | O(n) | Built-in, fast, simple JSON parsing |
| Newtonsoft.Json | O(n) | O(n) | Complex JSON, more features, legacy support |
| Dictionary | O(n) | O(n) | Simple JSON with string values only |
System.Text.Json for built-in JSON support without extra packages.Dictionary<string, string> causes errors if values are not strings.