Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Method for converting a Json.NET object into a dynamic CLR object.
// http://groups.google.com/group/mongodb-csharp/browse_thread/thread/ef1308f38bdbde3e
public static class DynamicUtils
{
public static object ConvertJTokenToObject(JToken token)
{
if (token is JValue)
{
return ((JValue)token).Value;
}
if (token is JObject)
{
ExpandoObject expando = new ExpandoObject();
(from childToken in ((JToken)token) where childToken is
JProperty select childToken as JProperty).ToList().ForEach(property =>
{
((IDictionary<string,
object>)expando).Add(property.Name, ConvertJTokenToObject(property.Value));
});
return expando;
}
if (token is JArray)
{
object[] array = new object[((JArray)token).Count];
int index = 0;
foreach (JToken arrayItem in ((JArray)token))
{
array[index] = ConvertJTokenToObject(arrayItem);
index++;
}
return array;
}
throw new ArgumentException(string.Format("Unknown token type
'{0}'", token.GetType()), "token");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.