Marid Marid - 1 month ago 4
JSON Question

C# Dictionary to Json Format

This Question is related to Json data format. I have a dictionary with Key value pair.
ConfigA 1200
ConfigB 1500
ConfigC 800
ConfigD 2
.I need to convert the all dictionary values to 1 json format
[{"ConfigA":"1200","ConfigB":"1500","ConfigC":"800","ConfigD":"2"}]
Could anyone help me how to do it ?

Answer

Add System.Web.Extensions.dll and try the below code,

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

public class Program
{
    public static void Main()
    {
        var dictionary = new Dictionary<string, int> {
            {"ConfigA", 1200},
            {"ConfigB", 1500},
            {"ConfigC", 800},
            {"ConfigD", 2}
        };

        var serializer = new JavaScriptSerializer();
        Console.WriteLine(serializer.Serialize(dictionary));
    }
}