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);
//and
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!

6 comments:

  1. Спасибо, Алексей!

    ReplyDelete
  2. i am getting this type of error:-
    An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

    Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.String]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

    To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

    Path 'productIdentifier', line 2, position 23.

    how to this..thnx in advance..please reply

    your regard

    ReplyDelete
    Replies
    1. It works fine for me. Can you show your code on pastebin.com, for example.

      Delete
  3. Hi ,

    thank you so much for your solution. I have just a small query. I take a grid data and try to deserialize Json String to Dictionary>. for the values i pass only the last grid row gets taken in and not the ones before that into the variable. Please help me with it.

    My code for the controller is as follow:

    public ActionResult JoinWhereInitial(String gridData)
    {
    Dictionary> result = new Dictionary>();
    Dictionary desirializedJsonObject = JsonConvert.DeserializeObject>(gridData);

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

    return Json("Update Successful");
    }



    the data that gets passed into the controller for griddata is as follow:

    "{\"5\":[\"TestColumn1\",\"\",\"TableNames\",\"TableID\",\"100\",\"\",\"VARCHAR\",\"\"],\"5\":[\"TestColumn2\",\"\",\"TableNames\",\"TableID\",\"100\",\"\",\"VARCHAR\",\"\"]}"

    ReplyDelete
    Replies
    1. To what type you are trying to deserialize JSON string? Your code was corrupted.

      Delete