November 15, 2013

Deserialize JSON to Dictionary

Passing JSON is a very popular way to get data from the UI. For deserializing I am using Json.Net You can download this package from the site above or use NuGet.

It works fine for converting JSON string to simple Dictionary<string, string> or  Dictionary<string, object>

string json = @"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
Dictionary<string, object> dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

But you can have a little problem with deserialization JSON string to Dictionary<string, List<string>> type. 
Explicit conversion like in an example failes. To solve this problem we should make conversion in two steps:
1. convert original string to Dictionary<string, object> as we have done before;
2. deserialize recieved object (which is also the JSON string) to the type List<string>.
string json = "{\"key1\":[\"value1\"],\"key2\":[\"value2\",\"value3\"]}";

Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
Dictionary<string, object> desirializedJsonObject = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

foreach (var obj in desirializedJsonObject)
 var value = JsonConvert.DeserializeObject<List<string>>(obj.Value.ToString());
 result.Add(obj.Key, value);

Looks pretty easy, but can take some time for a first. Happy coding!