RestSharp serialization to JSON, object is not using SerializeAs attribute as expected

前端 未结 5 1783
北荒
北荒 2020-11-30 11:36

I am using RestSharp (version 104.4 via NuGet) to make calls to a Rest Web Service. I have designed a set of objects (POCO) which matches resources exposed

5条回答
  •  醉酒成梦
    2020-11-30 11:39

    I came across this issue, and solved this a slightly different way than above, wanted to note it here.

    We have a factory class that builds all of our requests. Looks like the following

    public IRestRequest CreatePutRequest(string resource, TBody body)
    {
        var request = new RestRequest(resource)
        {
            Method = Method.PUT,
        };
    
        request.AddParameter("application/json", Serialize(body), ParameterType.RequestBody);
        return request;
    }
    

    Rather than use the AddJsonBody and AddBody methods against the request, both of which cause serialisation, I used AddParameter which will add the object you pass in without serialisation. I created a method called Serialise, which uses JSON.net to serialise our class.

    private object Serialize(T item)
    {
        return JsonConvert.SerializeObject(item);
    }
    

    This then allows us to use JSON.net's JsonProperty annotation above your propertys. Here is an example -

    public class Example
    {
    
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
    
        [JsonProperty(PropertyName = "created")]
        public DateTime Created { get; set; }
    
        [JsonProperty(PropertyName = "updated")]
        public DateTime Updated { get; set; }
    
    }
    

提交回复
热议问题