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
I ended up using a mix of both answers as none really nailed it.
ToObject() can do the first level of properties in a JSON object, but nested objects won't be converted to Dictionary().
There's also no need to do everything manually as ToObject() is pretty good with first level properties.
Here is the code:
public static class JObjectExtensions
{
public static IDictionary ToDictionary(this JObject @object)
{
var result = @object.ToObject>();
var JObjectKeys = (from r in result
let key = r.Key
let value = r.Value
where value.GetType() == typeof(JObject)
select key).ToList();
var JArrayKeys = (from r in result
let key = r.Key
let value = r.Value
where value.GetType() == typeof(JArray)
select key).ToList();
JArrayKeys.ForEach(key => result[key] = ((JArray)result[key]).Values().Select(x => ((JValue)x).Value).ToArray());
JObjectKeys.ForEach(key => result[key] = ToDictionary(result[key] as JObject));
return result;
}
}
It might have edge cases where it won't work and the performance is not the strongest quality of it.
Thanks guys!