-
-
Save Stephanvs/1886629 to your computer and use it in GitHub Desktop.
RestSharp deserialize JSON to dynamic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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