Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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" }
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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" }
// ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading