1

I am serializing and then deserializing a Dictionary in Newtonsoft.Json, however the output is not what I expected and is throwing exceptions. Can someone let me know what I'm doing wrong?

Here is my code

using Newtonsoft.Json;

namespace Task1
{
    public class Class1
    {
        public static void Main()
        {
            var dict = new Dictionary<string, object>();
            dict["int"] = new GenericItem<int> {CreatedAt = DateTime.Now, Object = 111};
            dict["string"] = new GenericItem<string> {CreatedAt = DateTime.Now.Date, Object = "test test"};

            var json = JsonConvert.SerializeObject(dict);
            var desDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

            var test = dict["int"] is GenericItem<int>;
            var test2 = dict["int"] as GenericItem<int>;
            var test3 = (GenericItem<int>) dict["int"];

            var desTest = desDict["int"] is GenericItem<int>;
            var desTest2 = desDict["int"] as GenericItem<int>;
            var desTest3 = (GenericItem<int>) desDict["int"];
        }

    }

    public class GenericItem<T>
    {
        public DateTime CreatedAt { get; set; }
        public T Object { get; set; }
    }
}

First three tests return True, Instance of GenericItem<Int> and again Instance of GenericItem<Int>.

But after deserialization return false, null, and InvalidCastException.

What is the problem? Why after deserealization does it throw InvalidCastException?

1
  • 3
    Welcome to SO, in the future a bit of background about what you are trying to do will help people answer your question quicker Commented May 3, 2014 at 22:32

3 Answers 3

4

What is the problem? Why after deserealization does it throw InvalidCastException?

The reason of this behaviour is simple - if you check the type of this element with desDict["int"].GetType(), you will see that it returns Newtonsoft.Json.Linq.JObject and that's definitely not the type you were expecting.

It is possible to do what you want with usage of TypeNameHandling parameter of JsonSerializerSettings class, as suggested in this SO answer. Change this:

var json = JsonConvert.SerializeObject(dict);
var desDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

to this:

var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;
var json = JsonConvert.SerializeObject(dict, settings);
var desDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, settings);

Info from reffered answer:

The TypeNameHandling flag will add a $type property to the JSON, which allows Json.NET to know which concrete type it needs to deserialize the object into. This allows you to deserialize an object while still fulfilling an interface or abstract base class.

The downside, however, is that this is very Json.NET-specific. The $type will be a fully-qualified type, so if you're serializing it with type info,, the deserializer needs to be able to understand it as well.

As an alternative you can loop throught the deserialized dictionary to convert values for each key from JObject to desired type:

var desDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
var newDict = new Dictionary<string, object>(); //as you can't modify collection in foreach loop and the original dictionary can be out of scope of deserialization code

foreach (var key in desDict.Keys)
{ 
    switch(key)
    {
        case "int":
            newDict[key] = ((JObject)desDict[key]).ToObject<GenericItem<int>>();
            break;
        case "string":
            newDict[key] = ((JObject)desDict[key]).ToObject<GenericItem<string>>();
            break;
    }
}

desDict = newDict;

You don't need that manual solution here, but maybe someday this knowledge will be useful. I found info about JOobject.ToObject() method in this SO answer. I've checked both methods and both work fine with the code you provided.

1
  • 1
    Thank you very much, Konrad! Now everything became clear to me. Commented May 4, 2014 at 8:31
1

You ask it to deserialize to a Dictionary<string, object> so it does so. It doesn't store the type information so it builds an object to store the deserialized information in.

I don't think you can get what you want, due to variance issues. You could deserialize to a Dictionary<string, GenericItem<object>> but that doesn't seem to be what you wanted. You get a json.net specific object in place of your int or string. You could cast that to what you want.

3
  • It doesn't build a dynamic type, JSON.Net contains its own type called a JObject.
    – Kyle Hale
    Commented May 3, 2014 at 22:47
  • Thank you. But how to deserialize string as Dictionary<string, GenericItem<T> > so get my scenario to work? Commented May 3, 2014 at 22:49
  • @KyleHale whoops my bad being loose on the terminology there.
    – Sign
    Commented May 3, 2014 at 23:05
-3

try :

var desDict = JsonConvert.DeserializeObject<Dictionary<string, GenericItem<object>>>(json);

or :

var desDict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);

using dynamic you don't need to cast your object at all, you can just use it's properties

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.