Turn ExpandoObject into static type

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!

As many others have shown, the new ExpandoObject introduced in C# 4 can be pretty useful in some scenarios.

However, on the odd occasion when you want to convert an ExpandoObject to a static type you have defined you can be forgiven for feeling a little lost as there are no well documented ways to do that. At least that’s how I felt, until I found out about the ConvertToType methods on the JavaScriptSerializer!

JavaScriptSerializer

The JavaScriptSerializer, like the DataContractJsonSerializer class, lets you serialize and deserialize objects to and from JSON string. But unlike the DataContractJsonSerializer class, you are not confined to working with types that are marked with the DataContract attribute.

One of the deserialization methods on the JavaScriptSerializer class – DeserializeObject – lets you a JSON string to an object graph, i.e. a Dictionary<string, object> object where the key is the name of the property and the value is the property value. And you can use one of the overloaded ConvertToType methods to convert this dictionary to a static type of your choice, provided that the type has a parameterless constructor (which unfortunately, means you won’t be able to convert an ExpandoObject to an anonymous type).

ExpandoObject as IDictionary<string, object>

Why is this important? It’s because the ExpandoObject implements the IDictionary<string, object> interface and therefore can be used with the ConvertToType methods!

Here’s what you do:

   1: // first you need to instantiate the serializer

   2: var jsSerializer = new JavaScriptSerializer();

   3:

   4: // get an expando object and convert it to an instance of MyClass

   5: var expando = GetExpandoObject();

   6: var obj = jsSerializer.ConvertToType<MyClass>(expando);

   7:

   8: Console.WriteLine(obj.Id);      // 0db9d9a6-8c7e-4bea-82a8-4d5641c7c0de

   9: Console.WriteLine(obj.Name);    // Yan

  10: Console.WriteLine(obj.Age);     // 29

  11:

  12: ...

  13:

  14: public ExpandoObject GetExpandoObject()

  15: {

  16:     dynamic expando = new ExpandoObject();

  17:     expando.Id = Guid.NewGuid();

  18:     expando.Name = "Yan";

  19:     expando.Age = 29;

  20:

  21:     return expando;

  22: }

  23:

  24: public class MyClass

  25: {

  26:     public Guid Id { get; set; }

  27:

  28:     public string Name { get; set; }

  29:

  30:     public int Age { get; set; }

  31: }

Pretty cool, eh? ;-)

But what if the shape of the expando object doesn’t match your type? E.g. there are properties defined on MyClass but not on the expando object, or vice versa, or both? Well, it’s smart enough to work that out itself and only set the properties which it is able to set:

   1: // same as before

   2:

   3: Console.WriteLine(obj.Id);          // 0db9d9a6-8c7e-4bea-82a8-4d5641c7c0de

   4: Console.WriteLine(obj.Name);        // null

   5: Console.WriteLine(obj.Age);         // 29

   6: Console.WriteLine(obj.NickName);    // null

   7:

   8: ...

   9:

  10: public ExpandoObject GetExpandoObject()

  11: {

  12:     dynamic expando = new ExpandoObject();

  13:     expando.Id = Guid.NewGuid();

  14:     expando.Name = "Yan";

  15:     expando.Age = 29;

  16:     expando.Wife = "Yinan";    // not defined on MyClass

  17:

  18:     return expando;

  19: }

  20:

  21: public class MyClass

  22: {

  23:     public Guid Id { get; set; }

  24:

  25:     public string Name { get; private set; } // non-public setter

  26:

  27:     public int Age { get; set; }

  28:

  29:     public string NickName { get; set; } // not defined on ExpandoObject

  30: }

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.


Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.


Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!


Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!