Search code examples
c#.net-corejson.netrestsharp

How to consume api that return json data as string using RestSharp RestClient in dot NET


I am consuming an API that returns json data as string. That is its return type is Task<string>. Generally API returns an object of Response class which is then serialized by dot NET. But in this case the API returns serialized version of Response class.

I am trying to consume this API using RestSharp->RestClient. In the RestClient method ExecutePostAsync<T>(request), the response is deserialized by the method into the object of class specified in place of T. I have class named Response class in which I want the response to be deserialized. So, I make the request as,

_restClient.ExecutePostAsync<Response>(request)

Now the problem I am facing is the json string returned in response by API is in form "{<json-fields>}", but when received to RestClient it is in form \"{<json-fields>}\". That is escape characters are added to it. So, NewtonSoftJSON which is used by RestClient to serialize and deserialize gives error, Error converting \"{<json-fields>}\" to Response class.

Also I need original RestResponse from RestClient as I am performing Validation on RestResponse. So, cannot do like, get response as string and deserialize it. That is I dont't want to do like,

var restResponse = _restClient.ExecutePostAsync<string>(request);
var data = Deserialize(restResponse.Data);

As this will only give me object of Response class but I need object of RestResponse<Response> class to perform validations.

What can I do in this situation?


Solution

  • Through some research on internet, I found following solution,

    We will initialize the RestClient and RestRequest as,

    RestClient restClient = new RestClient();
    RestRequest request = new RestRequest(<url>);
    

    Now as the response from api is json data in from of simple string, we can instruct request to accept text response as follows,

    restRequest.AddHeader("Accept", "text/plain");
    

    Now, RestClient by default doesn't use NewtonSoftJson deserialization for response type text/plain. So, we need to add a handler to tell RestClient to use NewtonSoftJson deserialization as follows,

    restClient.AddHandler("text/plain", () => new RestSharp.Serializers.NewtonsoftJson.JsonNetSerializer());
    

    Now we can make request as follows and it will work fine,

    restRequest.AddJsonBody(<body>);
    restClient.ExceutePostAsync<T>(restRequest);
    

    where we can replace T with class in which we want our response to be deserialized.

    References:

    https://github.com/restsharp/RestSharp/issues/276

    Deserialize JSON with RestSharp