Using JSON.Net to eval json into a dynamic variable in C#

So I thought this would be possible and finally decided to give it a shot in 2010 Beta 2. It turns a bunch of JSON into an ExpandoObject using JSON.Net.

Needs cleaning up but not too bad.

        [TestMethod]

        public void DeserializeTestObjectToDynamic(){

            TestObject testObject = new TestObject() {

                FirstName = "Peter",

                LastName = "Goodman",

                DateOfBirth = new DateTime(1979, 2, 3),

                Child = new TestChildObject {

                    Line1 = "child line 1",

                    Line2 = "child line 2",

                    Line3 = "child line 3",

                    City = "child city"

                },

 

                Children = new Collection<TestChildObject>() {

                    new TestChildObject() {

                    Line1 = "children 1 line 1",

                    Line2 = "children 1 line 2",

                    Line3 = "children 1 line 3",

                    City = "children 1 city"

                },

                new TestChildObject() {

                    Line1 = "children 2 line 1",

                    Line2 = "children 2 line 2",

                    Line3 = "children 2 line 3",

                    City = "children 2 city"

                }

                             }

 

            };

 

            // Get our json string

            string json = JsonConvert.SerializeObject(testObject);

 

            // Create the json.Net Linq object for our json string

            JObject jsonObject = JObject.Parse(json);

 

            // eval into an expando

            dynamic dynObject = ConvertJTokenToObject(jsonObject);

 

 

 

            Assert.IsNotNull(dynObject);

 

            Assert.IsNotInstanceOfType(dynObject, typeof(TestObject));

            Assert.IsInstanceOfType(dynObject, typeof(ExpandoObject));

 

            Assert.AreEqual(testObject.FirstName, dynObject.FirstName);

            Assert.AreEqual(testObject.LastName, dynObject.LastName);

            Assert.AreEqual(testObject.DateOfBirth, dynObject.DateOfBirth);

 

            Assert.IsNotNull(dynObject.Child);

            Assert.AreEqual(testObject.Child.Line1, dynObject.Child.Line1);

            Assert.AreEqual(testObject.Child.Line2, dynObject.Child.Line2);

            Assert.AreEqual(testObject.Child.Line3, dynObject.Child.Line3);

 

            Assert.IsNotNull(dynObject.Children);

            Assert.AreEqual(testObject.Children.Count, dynObject.Children.Length);

            for (int i = 0; i < testObject.Children.Count; i++) {

                Assert.AreEqual(testObject.Children[i].Line1, dynObject.Children[i].Line1);

                Assert.AreEqual(testObject.Children[i].Line2, dynObject.Children[i].Line2);

                Assert.AreEqual(testObject.Children[i].Line3, dynObject.Children[i].Line3);

            }

        }

 

        public 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");

        }

 

 

Print | posted @ Tuesday, October 27, 2009 10:22 AM

Comments on this entry:

Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C# Left by quebec incorporation at 5/24/2010 11:58 AM Gravatar I'll b
by fishing hat at 6/18/2010 9:06 PM

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. It is the old what goes around comes around routine. Did you want to acquired lots of links and I see lots of trackbacks??<br />
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by k&#252;rt&#231;e m&#252;zik dinle at 5/21/2010 8:55 PM

Thank you for your articles, and sharing..
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by quebec incorporation at 5/24/2010 10:58 AM

I'll be using your code on my website, actually!
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by asp at 5/27/2010 7:44 AM

i used your code in my site aspkodlari.com. and it is success. thanks.
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by Insurance Quotes at 4/6/2010 8:44 AM

It's really good tutorial.Thank you!
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by Dody Gunawinata at 4/11/2010 7:37 AM

hmm...Is there anyway to make it recursive so that any properties with array of objects are also processed?<br /><br />for example the following result maps.google.com/.../json
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by sa&#231; ekimi fiyatları at 5/13/2010 2:13 AM

Hi;<br />Unfortunately, although I realize I could not read the topic defalrca to help me in this regard would be glad if the mail.<br />mary lou<br />marylou23@gmail.com ....
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by Florian Hoornaar at 12/28/2009 5:03 AM

Cool stuff. Will you be able to query the dynObject using Linq?
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by Florian Hoornaar at 12/28/2009 5:18 AM

I updated your code a bit. Now it works with Linq as well. Let me know if you are interested.
Gravatar # re: Using JSON.Net to eval json into a dynamic variable in C#
by Jay Allard at 12/30/2009 8:17 AM

Very Handy... thanks!<br /><br />I made a slight change to eliminate the repetitive casting.<br /><br /> IDictionary&lt;string, object&gt; expando = new ExpandoObject();<br /> (from childToken in ((JToken)token) where childToken is JProperty select childToken as JProperty).ToList().ForEach(property =&gt;<br /> {<br /> expando.Add(property.Name, ConvertJTokenToObject(property.Value));<br /> });<br />

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 6 and 5 and type the answer here: