'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 1:[1]

In case that you can't fix the api to response in json format the only way I see is clean your string response:

var data = Deserialize(restResponse.Data.ToString.Replace('\"',(char)0));

Also you should check the RestSharp's documentation, you can make a request passing the [Type] to auto-deserialize the response:

var request = new CreateOrder("123", "foo", 10100);
// Will post the request object as JSON to "orders" and returns a 
// JSON response deserialized to OrderCreated  
var result = client.PostJsonAsync<CreateOrder, **OrderCreated**>("orders", request, cancellationToken);

I hope this helps! ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1