简体   繁体   English

在c#中反序列化json数组的字典

[英]Deserialize json array of dictionaries in c#

I have an array of dictionaries that I've created in javascript. 我有一系列字典,我用javascript创建。 After serializing to json I get the following string : 序列化为json后,我得到以下字符串:

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

I am having a hard time getting this deserialized into either a list or dictionary in c#. 我很难将这个反序列化到c#中的列表或字典中。

I've tried: 我试过了:

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\"}]";

Use List<KeyValuePair<int, string>> 使用List<KeyValuePair<int, string>>

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);

what i suggest is for try to see what actually your json represent. 我建议的是试着看看你的json代表什么。 You can create a class here on Json2CSharp and the use this class/List of this class (depend on whether your json is in the form of array or simple class object). 您可以在Json2CSharp上创建一个类,并使用此类/此类的List(取决于您的json是数组形式还是简单类对象)。

Just pass type to JsonConvert.DeserializeObject class type part. 只需将类型传递给JsonConvert.DeserializeObject类类型部分。 for example 例如

var output = JsonConvert.DeserializeObject<List<Class>>(json);

In your case is it just an array of Temp class 在你的情况下它只是一个Temp类的数组

public class Temp
{
    public string key { get; set; }
    public string value { get; set; }
}

Sp all you need is :- Sp你需要的是: -

var output = JsonConvert.DeserializeObject<List<Temp>>(json);

The you can convert this list to dictionary as suggested in other answer:- 您可以将此列表转换为字典,如其他答案所示: -

var dictionary = output.ToDictionary(x => x.Key, y => y.Value);

This always help me out. 这总能帮助我。 Hope it help you too. 希望它也能帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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