Created
February 22, 2012 12:22
-
-
Save rdingwall/1884642 to your computer and use it in GitHub Desktop.
RestSharp deserialize JSON to dynamic
This file contains hidden or 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 hidden or 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; |
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.
the link goes somewhere else
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 aboutwhere T : new()
for the same reason.