How to serialize a dictionary to an array of json objects

I have a dictionary as shown below:

var tableData = new Dictionary<string, string>();
tableData["name"] = "Sam";
tableData["city"] = "Wellington";
tableData["country"] = "New Zealand";

How can I convert the above dictionary to a serialized json data as below:

[
   {  "key": "name", "val": "Sam" },
   {  "key": "city", "val": "Wellington" },
   {  "key": "country", "val": "New Zealand" }
]

>Solution :

To convert a Dictionary to a JSON string, you can use the System.Text.Json namespace in C# to serialize the dictionary. Here is an example:

using System.Text.Json;

// ...

var tableData = new Dictionary<string, string>()
{
    { "name", "Sam" },
    { "city", "Wellington" },
    { "country", "New Zealand" },
};

// Convert the dictionary to a JSON string
string json = JsonSerializer.Serialize(tableData);

// The JSON string should look like this:
// [
//    {  "key": "name", "val": "Sam" },
//    {  "key": "city", "val": "Wellington" },
//    {  "key": "country", "val": "New Zealand" }
// ]

Note that in the JSON string, the keys and values in the dictionary are represented as object properties rather than as a list of key-value pairs. If you want the JSON string to look exactly like the one in your example, you will need to convert the dictionary to a list of objects before serializing it. Here is how you can do that:

using System.Linq;

// ...

var tableData = new Dictionary<string, string>()
{
    { "name", "Sam" },
    { "city", "Wellington" },
    { "country", "New Zealand" },
};

// Convert the dictionary to a list of objects
var list = tableData.Select(kvp => new { key = kvp.Key, val = kvp.Value }).ToList();

// Convert the list to a JSON string
string json = JsonSerializer.Serialize(list);

// The JSON string should now look like this:
// [
//    {  "key": "name", "val": "Sam" },
//    {  "key": "city", "val": "Wellington" },
//    {  "key": "country", "val": "New Zealand" }
// ]

Leave a Reply