序列化 JSON 字典<字符串、字符串>

本文关键字:字符串 JSON 字典 序列化 | 更新日期: 2023-09-27 18:34:13

我有以下代码,我希望结尾是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 读取的吗?

序列化 JSON 字典<字符串、字符串>

一个简单的

解决方法是不使用字典,而是使用自定义数据对象,可能具有一个属性:

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

现在,您可以序列化/反序列化此自定义类的列表。

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

          

您不能拥有具有使用相同字符串"name"的多个键的字典,因为第二个字典将覆盖第一个键的值。 相反,您需要创建一个对象数组,例如:

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