Import Json object from Javascript into C# with Dynamic keyword

I never really used the dynamic keyword in a real application. I did some tutorials but not much.

This week, I got a situation where I was getting from Silverlight a Json object that I did not want to create an object for.

string response = HtmlPage.Window.Invoke("GetMyJson").ToString();
MyObject data = (MyObject)JsonConvert.DeserializeObject(response);

But, I did not wanted to create the MyObject because it was just for transferring data; a simple DTO object. Instead, I used the dynamic keyword provided by .Net framework 4.0.

The dynamic keyword will be resolved in runtime and this give us the leverage to access property that might not exist. For example, “GetMyJson” function was returning a simple object with 2 properties “Abc” and “Def”.

{'Abc':'123','Def':'456'}

So, in the C# code, I simply called those properties from the dynamic object.

string response = HtmlPage.Window.Invoke("GetMyJson").ToString();
dynamic data = JsonConvert.DeserializeObject(response);
string s1 = data.Abc;
string s2 = data.Def;

This is pretty useful for accessing quickly some data from Json object.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.