MortenGR
MortenGR

Reputation: 833

Deserialize and serialize a dictionary<string, object> using JSON.NET

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

Upvotes: 4

Views: 1808

Answers (1)

MortenGR
MortenGR

Reputation: 833

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 :-).

Upvotes: 2

Related Questions