user19329953
user19329953

Reputation: 63

How to map a dynamic type to a dictionary for a JSON

I want to take a JSON string and map it to a dictionary so I can have access to its key-value pairs and then check the values after. I keep getting an error:

Unable to cast object of type Newtonsoft.Json.Linq.JObject to type System.Collections.Generic.IDictionary [System.String,System.Object].string

IDictionary<string, object> dict = (IDictionary<string, object>)source;

source is from the JSON string.

Upvotes: 0

Views: 919

Answers (1)

Yong Shun
Yong Shun

Reputation: 51125

Instead of explicit casting from JObject to Dictionary, use JObject.ToObject<T>().

IDictionary<string, object> dict = source.ToObject<Dictionary<string, object>>();

Upvotes: 1

Related Questions