1

In my ASP.net C# code, I have an IEnumerable container filled with objects of an anonymous type (which is loosely based on data from SQL).

Suppose that my code looks something like this:

var uics = entities.getData()
    .Select(x => new
        {
            id = x.id
            name = x.name
            age = x.age
        });
return Json(uics); //Serialize JSON in ASP.net MVC 3

This is very simple. When I serialize this to JavaScript, I get an array of objects, each having fields id, name, and age.

What I would like to do is serialize this data to a JavaScript Object with id as the index, with each object referenced by its index having fields name and age.

How can I accomplish this.

3
  • You mean you want an array, basically? So that the json will look like: [ "id1" : {name: name1, age: age1} , "id2" : {name, name2: age: age2}] ? Commented Apr 6, 2012 at 15:54
  • The JSON should look something like what you describe, @Alexander Commented Apr 6, 2012 at 15:56
  • Maybe this blog post can be of any help : west-wind.com/weblog/posts/2012/Mar/09/… Commented Apr 6, 2012 at 16:11

1 Answer 1

4

You can create an IDictionary and use it as the result of the action:

var uics = entities.getData()
    .ToDictionary(x => x.id, x => new { x.name, x.age });

return Json(uics); //Serialize JSON in ASP.net MVC 3

There is no need to explicitly specify the property names for the anonymous type used here, because the compiler defaults those to the name of the property used to provide a value (which in both cases here is the same).

Sign up to request clarification or add additional context in comments.

1 Comment

+1: This is the answer I'm looking for. I would like to add that I discovered as I implemented this answer that if your dictionary key is a strongly-typed GUID, you must first cast it to a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.