RestSharp showing Error of Cannot create an instance of an interface have to manually deserialize RestSharp showing Error of Cannot create an instance of an interface have to manually deserialize json json

RestSharp showing Error of Cannot create an instance of an interface have to manually deserialize


I ran into the same problem. In my case I created a custom object (in your case is Interest object), which had a ICollection list of objects. So, I remove that ICollection and make it as a List of objects. Check whether the Interest has any Interface related property and try make as concrete object property.

Check InternInterests and OfficeInterests property it might be using any kind of interface collection.


In my case I fix the issue with the following code:var client = new RestClient();client.AddHandler("application/json", NewtonsoftJsonSerializer.Default);client.BaseUrl = new System.Uri(Host);

Where the class NewtonsoftJsonSerializer is a custom deserializer:

using Newtonsoft.Json;using RestSharp.Deserializers;namespace IntegrationTests.Common{    class NewtonsoftJsonSerializer : IDeserializer    {        private Newtonsoft.Json.JsonSerializer serializer;        public NewtonsoftJsonSerializer(Newtonsoft.Json.JsonSerializer serializer)        {            this.serializer = serializer;        }        public string DateFormat { get; set; }        public string Namespace { get; set; }        public string RootElement { get; set; }        public T Deserialize<T>(RestSharp.IRestResponse response)        {            var content = response.Content;            return JsonConvert.DeserializeObject<T>(content);        }        public static NewtonsoftJsonSerializer Default        {            get            {                return new NewtonsoftJsonSerializer(new Newtonsoft.Json.JsonSerializer()                {                    NullValueHandling = NullValueHandling.Ignore,                });            }        }    }}

I hope this can help.


@JUVER Your handler does help - Thank you.2 comments:

  • You may want some error handling in Deserialize, otherwise errors endbeing masked as Deserialize errors and

  • private Newtonsoft.Json.JsonSerializer serializer; is never used. It can beremoved along with the constructor.

Here is Deserialize with some error handling:

public T Deserialize<T>(RestSharp.IRestResponse response){    if (response.StatusCode == HttpStatusCode.Unauthorized) throw new System.UnauthorizedAccessException();    if (response.StatusCode != HttpStatusCode.OK || !response.IsSuccessful) throw (new System.Exception(response.Content));    var content = response.Content;    return JsonConvert.DeserializeObject<T>(content);}