Convert a Dictionary to JSON String in C#

Bilal Shahid Jan 30, 2023 Jun 30, 2022
  1. The Basic Structure of a JSON String
  2. Use JsonConvert.SerializeObject() to Convert a Dictionary to JSON in C#
  3. Use a Custom Made Function to Convert a Dictionary to JSON in C#
  4. Use JavaScript Serializer in C# for .NET Webapps
Convert a Dictionary to JSON String in C#

So, how do we create a Dictionary in C#? In C#, we first import a package as follows.

using System.Collections.Generic;

And then, inside the declared MAIN function within the class, we declare the Dictionary object.

IDictionary<int, double> cgpas = new IDictionary<int, dictionary>();

Let’s go ahead now, and see how we can convert a Dictionary to JSON.

The Basic Structure of a JSON String

What is JSON? JSON stands for JavaScript Object Notation.

It uses a sort of structure where values are mapped to a key. So if we want to store a set of employees in a store, let’s say, we can proceed as follows.

{"employees" : {{"id" : 1 , "name" : "John"}, {"id" : 2, "name" : "Kevin"}}

Now the above-given example may be a bit complex. But let’s break it down.

We are defining JSON first because you can get an insight into its structure and be better at breaking down how the conversions stated later on occur.

So we kick off with "Employees", which is the KEY. And then, we see a curly bracket followed by 2 more curly brackets (close and open).

A curly bracket enclosure can also be called a set. It contains keys and values because we have only defined 2 different employees, JOHN and KEVIN; hence only two sets are defined.

These are enclosed in a bigger set, the value of the KEY EMPLOYEES. Hence, if we now tend to call the EMPLOYEES tag, we will receive this set as the value.

Use JsonConvert.SerializeObject() to Convert a Dictionary to JSON in C#

Let’s start by adding some values to the CGPA dictionary we just initialized a while back.

cgpas.Add(1, 3.4);
cgpas.Add(2, 3.13);
cgpas.Add(3, 3.01);

And if we want to get the value of, let’s say, ID 2, we can call a PRINT statement as follows.

Console.WriteLine("The CGPA of ID 2 is: " + cgpas[2]);

Here the ID is enclosed within square brackets, denoting the KEY. Now let’s convert using the JsonConvert call.

string js = JsonConvert.SerializeObject(cgpas);

Before running this code, make sure you have NewtonSoft.JSON downloaded. If you don’t, head over to their website, or if working in Visual Studio, go to Nuget Packages and install NewtonSoft.JSON to avoid any errors.

Now, let’s print the converted string easily here.

Console.WriteLine("The CGPAs are: " + js);

And the output is as follows.

The CGPAs are: {"1":3.4,"2":3.13,"3":3.01}

If you cannot find the SerializeObject definition, check if you call it from the JsonConvert class and not the JsonConverter from System.Text.Json. Do also check the installation of NewtonSoft.JSON.

Use a Custom Made Function to Convert a Dictionary to JSON in C#

Let’s look at another solution where we implement a function that takes a dictionary and converts it to a JSON string. It can be modified later to suit your needs, but let’s go ahead and use it for our IDICTIONARY CGPAS.

static string MyDictionaryToJson(IDictionary<int, double> dict)
        {
            var x = dict.Select(d =>
                string.Format("\"{0}\": {1}", d.Key, string.Join(",", d.Value)));
            return "{" + string.Join(",", x) + "}";
        }

Now, what’s going on here? Well, we pass the dictionary as a parameter.

You can notice that we have used IDICTIONARY and not DICTIONARY. IDICTIONARY inherits from DICTIONARY and has a few more handy extensions, so we have gone on with it.

However, basic functions remain the same. Inside the function, we format the string by mapping the KEY from the DICTIONARY and using brackets to express how values should be inside the string.

The brackets around {1} will map values simply as numbers or strings. However, if you tend to make it more expressive and complex, you can add square brackets like this: {[1]} and make it work.

This will print the values within square brackets. The rest returns the string in the proper formatting.

Now inside the MAIN function, make the same calls.

string js = MyDictionaryToJson(cgpas);

Console.WriteLine("The CGPAs are: " + js);

Output:

The CGPAs are: {"1": 3.4,"2": 3.13,"3": 3.01}

Use JavaScript Serializer in C# for .NET Webapps

Suppose you are using web applications that use C# as the core. In that case, you are better off following a LIST structure to define the objects and then using the JavaScriptSerializer() function to convert it to a string.

Use the namespaces defined below to avoid any syntax errors while compilation.

using System.Web.UI;
using System.Web.Script.Serialization;

Then, let’s go ahead and create the CGPA list.

var cgpas = new List<int, double>();
cgpas.Add(new CGPA() { ID = 1, CGP = 3.4});
cgpas.Add(new CGPA() { ID = 2, CGP = 3.13 });
cgpas.Add(new CGPA() { ID = 3, CGP = 3.01 });

Of course, we must also define the CGPA class to instantiate.

public class CGPA
    {
        public int ID { get; set; }
        public double CGP { get; set; }
    }

And then, we can convert it to a string as follows.

var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(cgpas);

You can print the serializedResult, which will be the string formatted from the LIST initialized.

You might have to play around with your code a little in web versions. Sometimes console versions will not work and be compatible entirely.

Hence, ensure that the functions, assemblies, and directives you are using match the version you are running.

You can modify the codes given above as to your suitability. Thank you for reading!

Author: Bilal Shahid
Bilal Shahid avatar Bilal Shahid avatar

Hello, I am Bilal, a research enthusiast who tends to break and make code from scratch. I dwell deep into the latest issues faced by the developer community and provide answers and different solutions. Apart from that, I am just another normal developer with a laptop, a mug of coffee, some biscuits and a thick spectacle!

GitHub

Related Article - Csharp Dictionary