2012-05-14 94 views
3

我有下面的代码,我想最终是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读取?

+0

逆向如何您添加到字典中。 dic.Add(“name”,a); 而不是 dic.add(a,“name”); – vinco83

+0

你不能扭转它;字典需要唯一的密钥,所以你不能重复添加“名称”。保留OP的断言“这是倒退的”......不,事实并非如此。这就是用JSON表示键/值对的字典的方式。 'json = JsonConvert.SerializeObject(list.Select(x => new {name = x}),Formatting.Indented);''更简单。这会生成并序列化一组只包含'name'属性的匿名对象。不需要声明明确的类型名称。 – Triynko

回答

2

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

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

现在你可以序列化/反序列化这个自定义类的列表。

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

+0

虽然如此,谢谢 –

3

由于第二个字符将覆盖第一个字符的值,因此不能使用具有多个键的字典使用同一个字符串“name”。相反,你需要创建像对象的数组:

[ 
    {"name": "the allman brothers"}, 
    {"name": "the beach boys"} 
] 
相关问题