2

我正在尝试使用 ajax 和 C# webmethod 定义 aoColumns。我的处理方式与传递服务器端数据的方式非常相似,使用我添加 List 行的 List> 数据结构。我的问题是这会产生如下字符串:

{\"aoColumns\":[[\"\\\"bVisible\\\": False\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"],[\"\\\"bVisible\\\": True\"]]}

这几乎是正确的,除了列定义使用方括号而不是{}. 我将如何生成正确的 JSON 文本?任何帮助是极大的赞赏!

4

1 回答 1

1

我假设您正在使用来自http://www.datatables.net/的数据表。如果我错了,请纠正我。

我不确定您是否在创建 JSON 字符串以返回 AJAX 调用或将其转换为服务器端可用的内容时遇到问题。

如果您要在 Web 方法中创建 JSON 字符串,我建议使用 Dictionary 类型,因为它们非常接近 JSON 字符串。要将 Dictionary 类型转换为 JSON 字符串,请使用以下命令:

var dictionary = new Dictionary<string, string>()
// add values here...
return new JavaScriptSerializer().Serialize(dictionary);

如果要将 JSON 字符串转换为 Dictionary 对象,请使用以下命令:

var dictionary = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonString);

Another thing I like to do is convert the dictionary into an array if I am going to be working with any keys or values since getting them from the dictionary can be a pain when you do not know the exact key value you want to work with.

For reference, the JavaScriptSerializer is part of the System.Web.Script.Serialization.JavaScriptSerializer namespace and in the System.Web.Extensions assembly.

于 2011-07-01T22:58:42.283 回答