Search code examples
.netreflectionjson.netrestsharp

Cannot deserialize Restsharp response when the response is a raw string


I have a method similar to this where I execute requests and deserialize generic objects.

public T Execute<T>(RestRequest request) where T : new()
{
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request
    var response = _client.Execute<T>(request);

    return response.Data;
}

The responses are deserialized like this:

public T Deserialize<T>(IRestResponse response) => return JsonConvert.DeserializeObject<T>(response.Content);

I also have a class like this:

public class SomeResponse
{
    public string Id { get; set; }
}

The problem is that I cannot deserialize the response for some requests since for some reason it is only a raw string not inside a JSON object. The response looks like this:

"abc123"

Most of the API that I am fetching data from is returning JSON objects so it works fine. I would like to avoid creating another Execute method just for that edge case.

I have started something like this but it seems a bit hacky. I feel there should be a simpler way to do this

 public T Deserialize<T>(IRestResponse response)
 {
        try
        {
            return JsonConvert.DeserializeObject<T>(response.Content);
        }
        catch
        {
            var content = response.Content;
            response.Content = $"{{ \"Id\" : {response.Content} }}";
            return JsonConvert.DeserializeObject<T>(response.Content);
        }        
 }

Solution

  • I have solved this using this method for now. There is only one method that returns a raw string. A better solution is still appreciated.

    public T Deserialize<T>(IRestResponse response)
    {
        try
        {
            return JsonConvert.DeserializeObject<T>(response.Content);
        }
        catch
        {
            if (typeof(T) != typeof(SomeResponse))
            {
               throw;
            }
            response.Content = $"{{ \"Id\" : {response.Content} }}";
            return JsonConvert.DeserializeObject<T>(response.Content);
         }
    }
    

    other alternative is this

    public T Deserialize<T>(IRestResponse response)
    {
        if (typeof(T) == typeof(SomeResponse))
        {
            response.Content = $"{{ \"Id\" : {response.Content} }}";
        }
        return JsonConvert.DeserializeObject<T>(response.Content);
    }