Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gracefully handling an empty json object in RestSharp

Tags:

c#

.net

restsharp

I have the following code:

public void GetJson()
{
    RestRequest request = new RestRequest(Method.GET);

    var data = Execute<Dictionary<string, MyObject>>(request);
}

public T Execute<T>(RestRequest request) where T : new()
{
    RestClient client = new RestClient(baseUrl);
    client.AddHandler("text/plain", new JsonDeserializer());

    var response = client.Execute<T>(request);

    return response.Data;
}

The problem is that sometimes the response will be an empty json array []. And when I run this code I get the following exception: Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.

Is there a way to gracefully handle this?

like image 361
Thomas Avatar asked Jul 16 '12 23:07

Thomas


1 Answers

I worked around a similar issue myself in the following way. I had tried using custom deserializers (since I was deserializing to a complex object) but in the end the following was much simpler, as it only applied to one of the many kinds of requests I was making.

request.OnBeforeDeserialization = (x =>
{
    x.Content = x.Content.Replace("[]", "{}");
});

Where I was constructing the request object for this particular request, I used the OnBeforeDeserialization property to set a callback which replaces the incorrect [] with {}. This works for me because I know the data I'm getting back in the rest of x.Content will never contain [] except in this specialized case, even in the values.

This might help someone else, but should definitely be used with care.

like image 74
xan Avatar answered Nov 08 '22 18:11

xan