Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i map a json string to a dictionary from a dynamic type

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`2[System.String,System.Object]’." string

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

source being the json string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading