How to use Newtonsoft.Json for Dynamic and ExpandoObject objects?

In this post, I’ll explain you how to use Newtonsoft.Json for Dynamic and ExpandoObject objects. It can be useful for some cases. Please refer to my recent post, if you would like to learn about Serialization and Deserialization fundamentals using Newtonsoft.Json.

What is ExpandoObject?

An object of type ExpandoObject is an object whose members can be dynamically added and removed at run-time. This type resides in System.Dynamic namespace.

What is Dynamic in C#?

Dynamic basically represents an object whose operations will be resolved at run-time.

I’m using a console application and my Program.cs file looks like this:

As you can see above, I’ve got a class named DynamicExpandoObjectDemo that has a static method named ShowDemo that looks like this:

Let us now understand the code above.

  • Line no. 5 creates a dynamic object of type ExpandoObject which has no members defined at this time.
  • Line no. 6-8, adds three new members to this new object.
  • Next, on line no. 10, the object is serialized with a formatting option so that the output is properly formatted in the console. The result that we get back is of type string.
  • Then the same string object is used for deserialization on line no. 13. Notice that the deserialize method is not using any specific type and the object named newAuthor is dynamic.

The output of this program look like below in the console:

As you can see it is very simple to deal with data when its concrete type is not known. ExpandoObject and dynamic objects are really powerful but at the same time it is more prone to risk. Always ensure that you have guard clauses/checks in place before you try to get a member from an dynamic object.

I hope this explains how to use Newtonsoft.Json for Dynamic and ExpandoObject objects.

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger