反序列化在C#中词典JSON数组

问题描述:

我有,我已经在JavaScript创建字典的数组。经过序列化到JSON我得到以下字符串:

I have an array of dictionaries that I've created in javascript. After serializing to json I get the following string :

"[{\"key\":\"60236\",\"value\":\"1\"},{\"key\":\"60235\",\"value\":\"gdsfgdfsg\"},{\"key\":\"60237\",\"value\":\"1\"}]"

我有一个很难得到这种反序列化到C#或者列表或字典。

I am having a hard time getting this deserialized into either a list or dictionary in c#.

我试过:

Dictionary<int, string> values = JsonConvert.DeserializeObject<Dictionary<int, string>>(Model.Json);



但是,这并不正常工作。

but that doesn't work.

有几种方法,你可以提取您的键/值对构建词典:

There are several ways that you can extract your key/value pairs to construct a dictionary:

var dict = "[{\"key\":\"60236\",\"value\":\"1\"},  
             {\"key\":\"60235\",\"value\":\"gdsfgdfsg\"},
             {\"key\":\"60237\",\"value\":\"1\"}]";

使用列表&LT; KeyValuePair&LT; INT,串&GT;&GT;

var dictionary = JsonConvert.DeserializeObject<List<KeyValuePair<int, string>>>(dict)
                                 .ToDictionary(x => x.Key, y => y.Value);

使用代表您对自定义的对象,然后创建一个字典,从您的收藏。

Use a custom object that represents your pairs and then create a dictionary from your collection.

var output = JsonConvert.DeserializeObject<List<Temp>>(dict);
var dictionary = output.ToDictionary(x => x.Key, y => y.Value);

public class Temp
{
    public int Key { get; set; }
    public string Value { get; set; }
}



最后,如果你使用一个自定义的不舒服暴殄天物的对象。只为反序列化,你可以把一个微小的性能损失,并使用动态而不是

Finally, if you're uncomfortable with using a custom "throwaway" object just for deserialization, you can take a tiny performance hit and use dynamic instead.

var dictionary = JsonConvert.DeserializeObject<List<dynamic>>(dict)
                                 .ToDictionary (x => (int)x.key, y => (string)y.value);