How to convert object to Dictionary<TKey, TValue> in C#?

.net, c#, dictionary, object

Solution

I found it easy to serialize the object into JSON and deserialize as a dictionary with Newtonsoft's Json.NET (`using Newtonsoft.Json`):

var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

I don't know how performance is effected but this is much easier to read. You could also wrap it inside a function.

public static Dictionary<string, TValue> ToDictionary<TValue>(object obj)
{       
    var json = JsonConvert.SerializeObject(obj);
    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(json);   
    return dictionary;
}

Use like so:

var obj = new { foo = 12345, boo = true };
var dictionary = ToDictionary<string>(obj);

Problem

How do I convert a dynamic object to a `Dictionary<TKey, TValue>` in C# What can I do? ``` public static void MyMethod(object obj) { if (typeof(IDictionary).IsAssignableFrom(obj.GetType())) { // My object is a dictionary, casting the object: // (Dictionary<string, string>) obj; // causes error ... } else { // My object is not a dictionary } } ```

Original source

Related problems