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"}]