【发布时间】:2012-05-14 23:24:09
【问题描述】:
我有以下代码,我希望结尾是 JQuery 自动完成可以读取的 JSON。
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static string GetNames(string prefixText, int count)
{
Trie ArtistTrie = (Trie)HttpContext.Current.Cache["CustomersTrie"];
List<string> list = ArtistTrie.GetCompletionList(prefixText, 10);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (string a in list)
{
dic.Add(a, "name");
}
string json = JsonConvert.SerializeObject(dic, Formatting.Indented);
return json;
}
JSON 看起来像这样:
{
"the album leaf": "name",
"the all-american rejects": "name",
"the allman brothers band": "name",
"the animals": "name",
"the antlers": "name",
"the asteroids galaxy tour": "name",
"the avett brothers": "name",
"the band": "name",
"the beach boys": "name",
"the beatles": "name"
}
这是倒退,我想要
"name" : "the allman brothers"
但是....字典需要一个唯一的键,相同的值是可以的,
这个问题有什么简单的解决方法,也可以从 JQuery 中读取吗?
【问题讨论】:
-
反转您添加到字典的方式。 dic.Add("名称", a);而不是 dic.add(a, "name");
-
你不能只是反转它;字典需要唯一键,因此您不能重复添加“名称”。维护 OP 的断言“这是倒退”......不,不是。这就是在 JSON 中表示键/值对字典的方式。只做
string json = JsonConvert.SerializeObject(list.Select(x => new {name = x}), Formatting.Indented);更简单。这会生成并序列化一组仅具有“名称”属性的匿名对象。无需显式声明类型名称。
标签: c# asp.net jquery-autocomplete json.net