简体   繁体   中英

Serialize JSON Dictionary<string, string>

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?

You can't have a dictionary with multiple keys using the same string "name" because the second one will overwrite the value of the first one. Instead you'll need to create an array of objects like:

[
  {"name": "the allman brothers"},
  {"name": "the beach boys"}
]

An easy fix for this is NOT to use a dictionary and instead use a custom data object, possibly with one property:

class Album
{
  public string Name{get;set;}
}

Now you can Serialize/Deserialize a list of this custom class.

 string json = JsonConvert.SerializeObject(YourListOfAlbum, Formatting.Indented);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM