Object Initializer syntax to produce correct Json

Tags: json linq c#
By : zadam
Source: Stackoverflow.com
Question!

I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.

Given this data:

var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");

And this code: ** Which is not correct and is what needs to be fixed!! **

var shaped = data.Select(c =>
    new { c = c }
).ToList();

serializer.Serialize(shaped,sb);
string desiredResult = sb.ToString();

I would like desiredResult to be:

{
    "One": "One",
    "Two": "Two",
    "Three": "Three"
}

but it is currently:

{ "c" : "One" },{ "c" : "Two" }, etc.

One problem is that on the left side of the object initializer I want the value of c, not c itself...

By : zadam


Answers

I'm replying to this old question just because all the other responses are basically wrong or incomplete.

JSON is really simple, so basically, to get the JSON you want, you need to grasp just the difference between JSON arrays:

["one", "two", "three"]

and JSON objects/dictionaries (objects and dictionaries are really the same):

{"a": "one", "b": "two", "c": 3}

Please note the "c" element is of different type, but this is not a problem for Javascript.

Given this, almost every serializer I use under .NET (which is almost always the great JSON.NET library) converts .NET objects or .NET dictionaries to JSON objects.

So what you need is to convert a List to a Dictionary, and then feed the serializer with a dictionary or object. Another question is why you would like to have a dictionary with value equal to the key, but I'll accept that point even if I'm quite dubious.

Example given:

        List<string> source = new List<string>() { "a", "b", "c" };

        Dictionary<string, string> dict = source.ToDictionary(el => el, el => el);

        var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
        // jsonString should be "{'a':'a', 'b':'b', 'c':'c'}", with more or less whitespace depending on formatting
By : A. Chiesa


What about using JSON.NET ?

By : mathieu


Solution offered for correctness, not performance.

        List<string> data = new List<string>()
        {
            "One",
            "Two",
            "Three"
        };

        string result =
            "{ "
            +
            string.Join(", ", data
              .Select(c => @"""" + c + @""": """ + c + @"""")
              .ToArray()
            ) + " }";
By : David B


This video can help you solving your question :)
By: admin