Skip to content

Instantly share code, notes, and snippets.

@mowen
Created September 13, 2010 19:29
Show Gist options
  • Save mowen/577859 to your computer and use it in GitHub Desktop.
Save mowen/577859 to your computer and use it in GitHub Desktop.
// 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