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

tucaz picture tucaz · Feb 15, 2013 · Viewed 86.8k times · Source

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!

Answer

Daniel A.A. Pelsmaeker picture Daniel A.A. Pelsmaeker · Feb 15, 2013

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);