-1

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 ?

Bjorn Reppen
  • 22,007
  • 9
  • 64
  • 88
Marid
  • 83
  • 10
  • use newtonsoft. http://www.newtonsoft.com/json/help/html/DeserializeDictionary.htm – Bryan Dellinger Nov 05 '16 at 10:33
  • Possible duplicate of [How do I convert a dictionary to a JSON String in C#?](http://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c) – Bjorn Reppen Apr 28 '17 at 10:36

2 Answers2

1

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));
    }
}
Aruna
  • 11,959
  • 3
  • 28
  • 42
0

Possibly same as this question

Just out of interest, do you know that you are creating an array containing a single object with 4 parameters? Assuming JavaScript will be the target of this structure then you will be referencing data[0].config*. You may want to leave off the square brackets at start and end to make the recipient JS code easier to understand. Example of before and after below.

// using array
var data = jQuery.parseJSON('[{"ConfigA":"1200","ConfigB":"1500","ConfigC":"800","ConfigD":"2"}]')

var A = data[0].configA
alert('Value of A=' + A)  // Will show 1200

var B = data[0].configB
alert('Value of B=' + B)  // Will show 1500

// without array
var dataV2 = jQuery.parseJSON('{"ConfigA":"1200","ConfigB":"1500","ConfigC":"800","ConfigD":"2"}')

var A2 = data.configA
alert('Value of A2=' + A2)  // Will show 1200

var B2 = data.configB
alert('Value of B2=' + B2)  // Will show 1500
Community
  • 1
  • 1
Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67