Skip to content

Instantly share code, notes, and snippets.

@Stephanvs
Forked from rdingwall/DynamicJsonDeserializer.cs
Created February 22, 2012 18:54
Show Gist options
  • Save Stephanvs/1886629 to your computer and use it in GitHub Desktop.
Save Stephanvs/1886629 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment