我有下面的代码,我想最终是JSON自动完成可以读取的JSON。序列化JSON字典<string,string>
[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"
但是....字典需要一个唯一的密钥,并且一致的值都OK ,
什么是这个简单的修复,这也可以从JQuery读取?
逆向如何您添加到字典中。 dic.Add(“name”,a); 而不是 dic.add(a,“name”); – vinco83
你不能扭转它;字典需要唯一的密钥,所以你不能重复添加“名称”。保留OP的断言“这是倒退的”......不,事实并非如此。这就是用JSON表示键/值对的字典的方式。 'json = JsonConvert.SerializeObject(list.Select(x => new {name = x}),Formatting.Indented);''更简单。这会生成并序列化一组只包含'name'属性的匿名对象。不需要声明明确的类型名称。 – Triynko