在ASP.NET Web API中将字典序列化为JSON数组

3
我想使用ASP.NET Web API将Dictionary序列化为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"}] 
2个回答

3
在JavaScript中,你所谓的“数组”必须是一个对象,其中索引是基于0的整数。但这并不是你现在的情况。你有id为3和4的元素,它们不能用作javascript数组的索引。所以,在这里使用List是正确的方法。
因为如果你想使用任意的索引(如在你的情况下有一些非基于0的整数),这不再是一个数组,而是一个对象,其中这些整数或字符串只是该对象的属性。这就是使用Dictionary要实现的目的。

0
你可以使用原始的JS代码将对象转换为数组。
var jsonFromServer = {"3":{"id":3,"name":"test3"},"4":{"id":4,"name":"test4"}};
var expected = [];
Object.keys(jsonFromServer).forEach(key => expected[+key] = json[key]);

console.log(expected.length); // 5
console.log(expected[0]);     // undefined
console.log(expected[1]);     // undefined
console.log(expected[2]);     // undefined
console.log(expected[3]);     // Object { id: 3, name: "test3" }
console.log(expected[4]);     // Object { id: 4, name: "test4" }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接