简体   繁体   中英

Deserialize json array of dictionaries in c#

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

I am having a hard time getting this deserialized into either a list or dictionary in 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>>

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

Just pass type to JsonConvert.DeserializeObject class type part. for example

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

In your case is it just an array of Temp class

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

Sp all you need is :-

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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