Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JObject into Dictionary<string, object>. Is it possible?

I have a web API method that accepts an arbitrary json payload into a JObject property. As such I don't know what's coming but I still need to translate it to .NET types. I would like to have a Dictionary<string,object> so that I can deal with it any way I want to.

I have searched a lot, but couldn't find anything and ended up starting a messy method to do this conversion, key by key, value by value. Is there an easy way to do it?

Input ->

JObject person = new JObject(     new JProperty("Name", "John Smith"),     new JProperty("BirthDate", new DateTime(1983, 3, 20)),     new JProperty("Hobbies", new JArray("Play football", "Programming")),     new JProperty("Extra", new JObject(         new JProperty("Foo", 1),         new JProperty("Bar", new JArray(1, 2, 3))     ) ) 

Thanks!

like image 402
tucaz Avatar asked Feb 15 '13 00:02

tucaz


1 Answers

If you have JObject objects, the following might work:

JObject person; var values = person.ToObject<Dictionary<string, object>>(); 

If you do not have a JObject you can create one with the Newtonsoft.Json.Linq extension method:

using Newtonsoft.Json.Linq;  var values = JObject.FromObject(person).ToObject<Dictionary<string, object>>(); 

Otherwise, this answer might point you in the right direction, as it deserializes a JSON string to a Dictionary.

var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); 
like image 151
Daniel A.A. Pelsmaeker Avatar answered Sep 22 '22 20:09

Daniel A.A. Pelsmaeker