Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 in the API. However, my objects property names does not match those expected by the Rest Service when posting data, so I would like to "transform" them when I make a request to the Rest service to make them match match. I read that adding SerializeAs attribute (with a Name specified) on my POCO's property will make them serialize correctly, but it won't.

My POCO

Imports RestSharp.Serializers

<Serializable(), SerializeAs(Name:="ApiMember")>
Public Class ApiMember
    <SerializeAs(Name:="id")>
    Public Property Id As Integer?

    <SerializeAs(Name:="email")>
    Public Property EmailAddress As String

    <SerializeAs(Name:="firstname")>
    Public Property Firstname As String

    <SerializeAs(Name:="lastname")>
    Public Property Lastname As String
End Class

My Call to the API

Dim request As RestRequest = New RestRequest(Method.POST)
Dim member As ApiMember = new ApiMember()

member.EmailAddress = "[email protected]"

request.Resource = "members"
request.RequestFormat = DataFormat.Json
request.AddBody(member)

Dim client As RestClient = New RestClient()
client.BaseUrl = "http://url.com"
client.Authenticator = New HttpBasicAuthenticator("username", "password")
client.Execute(Of ApiGenericResponse)(request)

What ends up being posted

{"Id":null,"EmailAddress":"[email protected]","Firstname":null,"Lastname":null}

Notice the name of the properties does not match thoses I specified in SerializeAs (uppercases, name of EmailAddress)

Am I missing something ?

like image 690
MaxiWheat Avatar asked Feb 07 '14 17:02

MaxiWheat


1 Answers

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".

like image 83
marc_s Avatar answered Oct 29 '22 14:10

marc_s