Created
September 13, 2010 19:29
-
-
Save mowen/577859 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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