【问题标题】:Serialize JSON Dictionary<string, string>序列化 JSON 字典<string, string>
【发布时间】: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 =&gt; new {name = x}), Formatting.Indented); 更简单。这会生成并序列化一组仅具有“名称”属性的匿名对象。无需显式声明类型名称。

标签: c# asp.net jquery-autocomplete json.net


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    你不能有一个包含多个键的字典使用相同的字符串“name”,因为第二个会覆盖第一个的值。相反,您需要创建一个对象数组,例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 2013-11-02
      • 2011-07-29
      • 2017-05-21
      相关资源
      最近更新 更多