SeanOB
SeanOB

Reputation: 782

RestSharp deserializing one property as null

I am using RestSharp to consume an API and deserialize the content on return. This is working fine for all but one of my objects properties:

"envId":":AU1:m:w:p:7:^W160216110747138.nev"

It is null in my c# object. I suspect the colons in the value are not playing nice, but I'm not sure.

As I test I implemented a JSON.NET deserialization to the same object, which parsed the property successfully. I'm assuming then that my c# class is fine, and it is the deserializer that is failing.

Below is the full rest method.

private static T HttpGet<T>(string url) where T : new()
    {
        var client = new RestClient(BaseApiUrl);
        client.Timeout = 1000 * 15;            
        client.ClearHandlers();
        client.AddHandler("application/json", new JsonDeserializer());

        var request = new RestRequest(url, Method.GET);
        request.AddHeader("Authorization", "Bearer " + App.Current.Properties["AccessToken"]);

        // Does not parse EnvID property
        IRestResponse<T> returnObject = client.Execute<T>(request);

        // Testing JSON.NET deserialization - does parse EnvID property
        var content = returnObject.Content;
        var test = JsonConvert.DeserializeObject<T>(content);
        //

        return returnObject.Data;
    }

Implementation is

string url = //url string here
StorageObject results = HttpGet<StorageObject>(url);

Below here is the class I am deserializing too (I've left most of the properties out, I'm having no issue with all of the others)

public class StorageObject
{
    public StandardAttribute StandardAttributes { get; set; }

    public List<CustomAttribute> CustomAttributes { get; set; }


    public StorageObject() {            
        CustomAttributes = new List<CustomAttribute>();
    }     

}

 public class StandardAttribute
{
    public string EnvID { get; set; }
    public string ID { get; set; }    
}

Finally, I am contemplating still using RestSharp to 'Execute' the rest calls, but deserializing the response content with JSON.NET to get around this. I noticed a warning about using JSON.NET when installing the latest version of RestSharp but I'm not sure what the risks are.

Upvotes: 1

Views: 1386

Answers (1)

Attila Szasz
Attila Szasz

Reputation: 3073

Since RestSharp switched from JSON.NET to their own serializer, I've found more then one case where it was failing to correctly deserialize responses from well known APIs. It's easy to use your own serializer/deserializer, just implement the ISerializer and IDeserializer interfaces.
See an example implementation using JSON.NET.

Upvotes: 2

Related Questions