Restsharp: deserialize json object with fewer fields than some class

I am using Restsharp to deserialize some of the webservice responses, however the problem is that sometimes these web services send a json response with multiple fields. I still manage to do this by adding all possible fields to my fit model, but this webservice will keep adding / removing fields from its answer.

For example:

Json answer that works:

{
    "name": "Daniel",
    "age": 25
}

      

Matching model:

public class Person
{
    public string name { get; set; }
    public int age { get; set; }
}

      

This works great: Person person = deserializer.Deserialize<Person>(response);

Now, suppose the json response is:

{
        "name": "Daniel",
        "age": 25,
        "birthdate": "11/10/1988"
}

      

See the new bithdate field . Now things are not going well. Is there a way to tell restsharp to ignore those fields that are not in the model?

+3


source to share


1 answer


If there are many changes in the fields you are returning, perhaps a better approach is to skip the static DTOs and deserialize before dynamic

. This gist gives an example of how to do it with RestSharp by creating your own deserializer:

// 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);
        }
    }
}

      

Using:

// 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;

      



An easier alternative is to use Flurl.Http (disclaimer: I'm the author), an HTTP client client that deserializes to dynamic

the default when no generic arguments are provided:

dynamic d = await "http://api.foo.com".GetJsonAsync();

      

In both cases, the actual deserialization is done by Json.NET . With RestSharp, you will need to add the package to your project (although you have another chance); Flurl.Http has a dependency on it.

+2


source







All Articles