Skip to content

Instantly share code, notes, and snippets.

@denolfe
Forked from rdingwall/DynamicJsonDeserializer.cs
Last active January 9, 2018 20:23
Show Gist options
  • Save denolfe/5771ad0b0258a28a657f761a6d94d809 to your computer and use it in GitHub Desktop.
Save denolfe/5771ad0b0258a28a657f761a6d94d809 to your computer and use it in GitHub Desktop.
RestSharp deserialize JSON to dynamic #snippet
// 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