Deserialize multiple response types with RestSharp

RestSharp

A typical REST request may return different objects on whether it is a successfull (200 OK) or a bad request (400)

One way to handle it - is to manually deserialize the "Content" string with JsonConvert to JsonSerializer, however, it requires us to explictly use a specific JSON library

Here is a better way:


RestClientOptions restClientOptions = new()
{
	BaseUrl = new Uri("https://someservice"),
};

RestClient restClient = new(restClientOptions);

RestRequest restRequest = new ("resource", Method.Get);

RestResponse restResponse = await restClient.ExecuteAsync(restRequest);

if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
{
	RestResponse<SuccessObject> successObjectResponse = restClient.Deserialize<SuccessObject>(restResponse);
    //Do something with succesObjectResponse.Data
}
else if (restResponse.StatusCode == System.Net.HttpStatusCode.BadRequest) 
{
	RestResponse<ErrorObject> errorObjectResponse = restClient.Deserialize<ErrorObject>(restResponse);
    //Do something with errorObjectResponse.Data
}

Post a Comment

Previous Post Next Post