Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize json array of dictionaries in c#

Tags:

json

c#

json.net

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.

like image 201
John Avatar asked May 21 '15 21:05

John


Video Answer


2 Answers

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);
like image 76
David L Avatar answered Oct 11 '22 14:10

David L


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.

like image 33
loop Avatar answered Oct 11 '22 13:10

loop