Skip to content

Instantly share code, notes, and snippets.

@rdingwall
Created February 22, 2012 12:22
  • Star 16 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rdingwall/1884642 to your computer and use it in GitHub Desktop.
RestSharp deserialize JSON to dynamic
// ReSharper disable CheckNamespace
namespace RestSharp.Deserializers
// ReSharper restore CheckNamespace
{
public class DynamicJsonDeserializer : IDeserializer
{
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public T Deserialize<T>(RestResponse response) where T : new()
{
return JsonConvert.DeserializeObject<dynamic>(response.Content);
}
}
}
// Override default RestSharp JSON deserializer
client = new RestClient();
client.AddHandler("application/json", new DynamicJsonDeserializer());
var response = client.Execute<dynamic>(new RestRequest("http://dummy/users/42"));
// Data returned as dynamic object!
dynamic user = response.Data.User;
// Remember properties are actually Json.NET JObjects so you have to call .Value to retrieve their string contents.
string firstName = user.FirstName.Value;
string lastName = user.LastName.Value;
@ashes999
Copy link

To get this to work with 104.1, I had to change line 5 of DynamicJsonDeserializer.cs to use the interface (IRestResponse response) instead of the concrete class (RestResponse response). Also, I had to remove the generic constraint about where T : new() for the same reason.

@ashes999
Copy link

I've posted a blog post with a full(er) write-up here: http://www.csharpcity.com/2013/deserializing-to-dynamic-with-restsharp/ that links to this gist.

@Ofer-Gal
Copy link

the link goes somewhere else

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment