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...

Was it helpful?

Solution

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()
            ) + " }";

OTHER TIPS

In json, the "c" in "c" : "One" is the property name. And in the C# world, you can't create property names on the fly (ignoring System.ComponentModel).

Basically, I don't think you can do what you want.

What about using JSON.NET ?

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top