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

前端 未结 5 1731
北荒
北荒 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<TBody>(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>(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; }
    
    }
    
    0 讨论(0)
  • 2020-11-30 11:44

    RestSharp uses SimpleJson. This library doesn't know or respect the [SerializeAs] attribute (which is XML-only anyway), it just outputs the POCO's property name, unless it's compiled with #SIMPLE_JSON_DATACONTRACT defined, then you can use the [DataContract] attribute to rename properties.

    So your options seem to be to recompile the SimpleJson library with that define and decorate your properties with the [DataContract(Name="lowercasepropertyname")] attribute, or create a custom serializer that uses a JSON serializer that does respect other attributes as suggested in @Ryan's answer.

    0 讨论(0)
  • 2020-11-30 11:49

    You could use following method in the Client side. It is essentially using Newtonsoft deserializer instead of built-in RestSharp deserializer. Newtonsoft deserializer respects DataMember Name property or JsonProperty.

        private T Execute<T>(RestRequest request)
        {
            var response = _client.Execute(request);
            if (response.ErrorException != null)
                throw new Exception("Error:" + response.ErrorException);
    
            return (T)JsonConvert.DeserializeObject(response.Content, typeof(T));
        }
    
    0 讨论(0)
  • 2020-11-30 11:53

    This is for @MaxiWheat and anyone else interested in how to use JSON.NET as the JSON serializer in a RestSharp request. Basically, I used the approach described in this blog post by Patrick Riley:

    // create the request
    var request = new RestRequest(yourUrlHere, Method.POST) { RequestFormat = DataFormat.Json };
    
    // attach the JSON.NET serializer for RestSharp
    restRequest.JsonSerializer = new RestSharpJsonNetSerializer();
    

    and the RestSharpJsonNetSerializer is an implementation (less than 100 lines of code) from the JSON.NET guys (John Sheehan) that can be found on their Github pages

    With this setup, my problems went away and I was able to have a proper DTO with nice CamelCase properties, while the serialized JSON uses them in all "lowercase".

    0 讨论(0)
  • 2020-11-30 11:59

    In RestSharp 104.4, the default JsonSerializer doesn't use the [SerializeAs] attribute, as seen by reviewing the source code.

    One workaround to this is to create a custom serializer that uses the Json.NET JsonSerializer (a good example is here) and then decorate your properties with the [JsonProperty] attribute, like so:

    <JsonProperty("email")>
    Public Property EmailAddress As String
    
    0 讨论(0)
提交回复
热议问题