简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM