Deserializing to Dynamic with RestSharp

RestSharp is awesome. Go try it. I highly recommend it (it’s overall less code and simpler than WCF, at any rate).

Services may or may not provide a well-defined list of fields to you, the consumer, which doesn’t change. There are two design options with trade-offs:

Wrapper Classes: Create wrapper classes that convert expected fields in the JSON to a simple C# object. (Eg. for twitter, create a class with CreatedAt and Text for tweets, which expects the API to send created_at and text back.)

Dynamic Classes: Use the new DLR, don’t care about static typing and expecting fields at runtime. Take whatever you get, and expose it.

For the second option, you need to sort out how to make RestSharp deserialize to (in the case of Twitter tweets) List<dynamic>.

Assuming you already have this working with a wrapper class, you only need to make a couple of changes. First, add a handler with a deserializer, as per this gist:

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.