Quantcast
Channel: Platform – C# City
Viewing all articles
Browse latest Browse all 16

Deserializing to Dynamic with RestSharp

$
0
0

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!


Viewing all articles
Browse latest Browse all 16

Trending Articles