4

If I have a dictionary and add e.g. an instance of a class MyClass to this dictionary, how do I make sure that a deserialization and serialization of the dictionary contains the class and not a JObject?

internal class MyClass
{
    public string MyProperty { get; set; }
}

[TestMethod]
public async Task DebugTest()
{
        Dictionary<string, object> testDictionary = new Dictionary<string, object>();
        testDictionary.Add("testkey", new MyClass() { MyProperty = "testproperty" });
        string json = JsonConvert.SerializeObject(testDictionary);
        Dictionary<string, object> restoredDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
    }

The testDictionary contains the MyClass, but the restoredDictionary contains a JObject.

Update: Please note that I will have to use string, object. So I'm really looking for a way to tell Json.Net to convert to a class and not JObject

3
  • Try var restoredDictionary = JsonConvert.DeserializeObject<Dictionary<string, MyClass>>(json); Commented May 8, 2017 at 11:10
  • replace your with testDictionary and restoredDictionary with Dictionary<string, MyClass>..Why you want to use object ? Commented May 8, 2017 at 11:25
  • I want to use string, object to catch different kind of objects (like MyClassA, MyClassB, etc.). It's part of a larger object model with ObjectConverters. That part works great, it is only the dictionary that is a problem. Commented May 8, 2017 at 11:33

1 Answer 1

2

The problem was that Json.Net has no way of knowing that an string, object deserialied and serialized again should be of a specific type. Luckily, there is an attribute called TypeNameHandling that tells Json.Net to save the type in the json string. Using this option for serializing and deserilizing worked perfectly :-).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.