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:

  1. 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.)
  2. 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:


namespace RestSharp.Deserializers
{
  public class DynamicJsonDeserializer : IDeserializer
  {
    public string RootElement { get; set; }
    public string Namespace { get; set; }
    public string DateFormat { get; set; }

    public T Deserialize<T>(IRestResponse response)
    {
      return JsonConvert.DeserializeObject<dynamic>(response.Content);
    }
  }
}

(You need JSON.NET for this.) When you build your RestClient instance, add the handler to it:


client.AddHandler("application/json", new DynamicJsonDeserializer());

Finally, deserialize it. The tricky part is deserializing. The DynamicJsonDeserializer class actually returns (in this case) a JArray instance. To convert that to List<dynamic>, you need to do this:


var response = client.Execute<JArray>(request).Data.ToObject<List<dynamic>>();

Et voila, you’re done! You now have a list of dynamic objects, and you can dynamically access their fields!

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.
This entry was posted in Libraries, Silverlight, Web, Wndows Forms, WPF and tagged , . Bookmark the permalink.

2 Responses to Deserializing to Dynamic with RestSharp

  1. Ben Northway says:

    Thank you very much for this! If you are trying to receive a singular object, you get a JObject instance instead of JArray instance.

  2. Pingback: How to: How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET? | SevenNet

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>