我想使用ASP.NET Web API将Dictionary序列化为JSON数组。为了说明当前的输出,我有如下设置:
当被序列化成JSON时,我得到了以下输出:
Dictionary<int, TestClass> dict = new Dictionary<int, TestClass>();
dict.Add(3, new TestClass(3, "test3"));
dict.Add(4, new TestClass(4, "test4"));
TestClass的定义如下:
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;
}
}
当被序列化成JSON时,我得到了以下输出:
{"3":{"id":3,"name":"test3"},"4":{"id":3,"name":"test4"}}
很遗憾,这是一个对象而不是一个数组。有没有办法实现我想做的事情?它不需要是字典,但我需要测试类的ID作为数组的键。
使用以下列表时,它会正确地序列化为一个数组,但没有正确的键。
List<TestClass> list= new List<TestClass>();
list.Add(new TestClass(3, "test3"));
list.Add(new TestClass(4, "test4"));
序列化为JSON:
[{"id":3,"name":"test3"},{"id":4,"name":"test4"}]