Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I would like to serialize a Dictionary to a JSON array with ASP.NET Web API. To illustrate the current output I have the following setup:

Dictionary<int, TestClass> dict = new Dictionary<int, TestClass>();
dict.Add(3, new TestClass(3, "test3"));
dict.Add(4, new TestClass(4, "test4"));

The TestClass is defined as follows:

public class TestClass
{
    public int Id { get; set; }
    public string Name { get; set; }

    public TestClass(int id, string name)
    {
        this.Id = id;
        this.Name = name;
    }
}

When serialized to JSON I get the following output:

{"3":{"id":3,"name":"test3"},"4":{"id":3,"name":"test4"}} 

Unfortunately this is an Object and not an Array. Is it somehow possible to achieve what I'm trying to do? It doesn't need to be a Dictionary but I need the Id's of the TestClass to be the Key's of the Array.

With the following List it is correctly serialized to an array but not with the correct Key's.

List<TestClass> list= new List<TestClass>();
list.Add(new TestClass(3, "test3"));
list.Add(new TestClass(4, "test4"));

Serialized to JSON:

[{"id":3,"name":"test3"},{"id":4,"name":"test4"}] 
share|improve this question

1 Answer 1

up vote 2 down vote accepted

but I need the Id's of the TestClass to be the Key's of the Array.

In javascript what you call an array must be an object in which the indexes are 0-based integers. This is not your case. You have id 3 and 4 which cannot be used as indexes in a javascript array. So using a List is the correct approach here.

Because if you want to use arbitrary indexes (as in your case you have some integers that are not 0-based) this is no longer an array but an object in which those integers or strings are simply the properties of this object. That's what you achieve with the Dictionary.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.