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:
1 2 3 4 5 6 7 8 9 10 11 |
class Program { static void Main(string[] args) { Console.Clear(); DynamicExpandoObjectDemo.ShowDemo(); Console.ReadLine(); } } |
As you can see above, I’ve got a class named DynamicExpandoObjectDemo
that has a static method named ShowDemo
that looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class DynamicExpandoObjectDemo { public static void ShowDemo() { dynamic author = new ExpandoObject(); author.Title = "Mr."; author.Name = "Sid"; author.City = "London"; var authorData = JsonConvert.SerializeObject(author, Formatting.Indented); Console.WriteLine(Environment.NewLine + authorData); dynamic newAuthor = JsonConvert.DeserializeObject(authorData); Console.WriteLine($"{Environment.NewLine}{newAuthor.Title} {newAuthor.Name} is from {newAuthor.City}"); } } |
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:
1 2 3 4 5 6 7 |
{ "Title": "Mr.", "Name": "Sid", "City": "London" } Mr. Sid is from London |
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.