I have the following code, I want the end to be JSON that a JQuery autocomplete can read.
[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;
}
The JSON looks like this:
{
"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"
}
This is backwards, I want
"name" : "the allman brothers"
but.... the dictionary needs a unique key, and identical values are ok,
What is an easy fix for this , also is this readable from JQuery?
string json = JsonConvert.SerializeObject(list.Select(x => new {name = x}), Formatting.Indented);. That generates and serializes a set of anonymous objects that just have a 'name' property. No need to declare explicit type names.