Convert Dictionary to JSON Object in .NET C# | Example Code

Learn how to convert a dictionary to a JSON object in .NET C# using the Newtonsoft.Json NuGet package. Follow our example code and get started with JSON serialization.

In C#, you can convert a dictionary to a JSON object using the Newtonsoft.Json NuGet package. Here’s an example:

using Newtonsoft.Json;

Dictionary<string, string> dict = new Dictionary<string, string>()
{
    {"key1", "value1"},
    {"key2", "value2"}
};

string json = JsonConvert.SerializeObject(dict);

Console.WriteLine(json);

This code will convert the dict dictionary to a JSON object and store it in the json string variable. You can then use this JSON object as needed. Note that you’ll need to include the using Newtonsoft.Json; statement at the top of your file in order to use the JsonConvert class.

If you run the code I provided, the output will be a JSON string representation of the dict dictionary, which will look like this:

{"key1":"value1","key2":"value2"}

This JSON string represents an object with two key-value pairs, where the keys are “key1” and “key2”, and the values are “value1” and “value2”, respectively.


Up ↑

%d bloggers like this: