Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RestSharp to deserialize different data outputs from one resource

I have quite generic webservice, which responds with many standard http statuses. However, it returns different types according to these statuses. This is completely proper REST implementation: I GET a Person entity with status 200 (OK), but when error occures, for example auth problem, I receive the 403 (Forbidden) with list of error messages (stating that token expired or my account is inactive, etc).

Unfortunately, using RestSharp I can only "bind" to one type of data which I should expect:

  client.ExecuteAsync<Person>(request, (response) =>
  {
        callback(response.Data);
  });

How should I capture the error messages, when status is different than 200? Of course, I could do this by hand and deserialize the response content myself, but I think there should be some cleaner, better way to accomplish that. I'd like to use something like this:

  client.ExecuteAsync<Person, ErrorList>(request, (response) =>
  {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Callback(response.Data);
        }
        else if (response.StatusCode == HttpStatusCode.OK)
        {
            ErrorCallback(response.Errors);
        }
  });
like image 396
jacek Avatar asked May 13 '13 21:05

jacek


1 Answers

The way that I've always handled it is to write a post processor for restsharp response. something like this,

public class Response<T>
{
  public T Data {get;set;}
  public List<Error> Errors {get;set;}
}

public static Response<T> GetResponse<T>(this IRestResponse restResponse)
{
        var response = new Response<T>();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            response.Data = JsonConvert.DeserilizeObject<T>(restResponse.Data)
        }

        response.Errors =JsonConvert.DeserilizeObject<List<Error>>(restResponse.Error)

        return response;
}

and you can use it like this,

var response = client.Execute(request).GetResponse<T>();
like image 80
kay.one Avatar answered Sep 28 '22 15:09

kay.one