RestSharp Deserialization of empty string to Dictionary Error

1.2k views Asked by At

I'm a bit new to RestSharp so please excuse my ignorance. I'm getting the following error:

 {"Unable to cast object of type 'System.String' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'."}

This happens when RestSharp tries to deserialize and empty string to a Dictionary object.

Here is the my abbreviated Result object:

public class Result
{
     public Dictionary<string, string> assignment_group { get; set; }
}

Here is what is returned if assignment_group is populated:

"assignment_group":{"link":"https://someurl/api/now/table/sys_user_group/2c1cf1176f29f5007a3db03f5d3ee4aa","value":"2c1cf1176f29f5007a3db03f5d3ee4aa"}

Here is what is returned if assignment_group is not populated:

"assignment_group":""

What is happening is the JSON response for assignment_group will be a Dictionary or an empty string. I will only get the error if it's an empty string. How can I accommodate both return types in my Result class assignment_group property?

Thanks in advance for any help out there.

Update: Here is working solution for me.

Instead of default Deserializer used by RestSharp, I used Newtonsoft.Json instead. Here is code example from my wrapper class:

 public T Execute<T>(RestRequest request) where T : new()
 {
        if (request.Method == Method.POST)
            client.FollowRedirects = false;

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

        // **** Added Newtonsoft.Json ****
        var x = JsonConvert.DeserializeObject<T>(response.Content);


        LogRequest(request, client);
        LogResponse<T>(response);

        ErrorHandling<T>(response);

       //  ****This is no longer needed. Data is null now****
       // return response.Data;  

       //  **** Added **** 
       return x;
 }
1

There are 1 answers

6
Geoffrey Owen On BEST ANSWER

Are you making use of a custom serializer/deserializer for this? Because my understanding is that the following cases are covered (but your example is not):

  1. assignment_group = null; results in "assignment_group":null
  2. assignment_group = new Dictionary(); results in "assignment_group" : "{}"
  3. assignment_group = new Dictionary(); assignment_group.Add("key","value"); results in "assignment_group" : "{"key":"value"}

This may also be related to: https://github.com/restsharp/RestSharp/issues/486