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
Sounds like a good use case for extension methods - I had something lying around that was pretty straightforward to convert to Json.NET (Thanks NuGet!):
Of course, this is quickly hacked together - you'd want to clean it up, etc.
public static class JTokenExt
{
public static Dictionary
Bagify(this JToken obj, string name = null)
{
name = name ?? "obj";
if(obj is JObject)
{
var asBag =
from prop in (obj as JObject).Properties()
let propName = prop.Name
let propValue = prop.Value is JValue
? new Dictionary()
{
{prop.Name, prop.Value}
}
: prop.Value.Bagify(prop.Name)
select new KeyValuePair(propName, propValue);
return asBag.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
if(obj is JArray)
{
var vals = (obj as JArray).Values();
var alldicts = vals
.SelectMany(val => val.Bagify(name))
.Select(x => x.Value)
.ToArray();
return new Dictionary()
{
{name, (object)alldicts}
};
}
if(obj is JValue)
{
return new Dictionary()
{
{name, (obj as JValue)}
};
}
return new Dictionary()
{
{name, null}
};
}
}