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

restsharp newtonsoft serializer
restsharp addjsonbody
restsharpjsonnetserializer
restsharp json serialize ignore null
c# serialize object to json
restsharp deserializeas
restsharp datetime serialization
restsharp deserialize byte array

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 = "me@example.com"

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":"me@example.com","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 ?


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

.net RestSharp serialization to JSON, object is not using SerializeAs , 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​  I was temporary switched to use Newtonsoft JSON serializer, which woks fine (using attribute [JsonProperty("mimeType")]) But, how can I specify serialization name using internal serializer? It's bug? I have latest version - 104.5.0.0


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; }

}

RestRequest.JsonSerializer = new JsonCustomSerializer<T>() not , .net RestSharp serialization to JSON, object is not using SerializeAs attribute as expected? // create the request var request = new RestRequest(yourUrlHere,  Please help me finding a way so that I can Serialize and De-serialize an object which contains Enum type property, using RestSharp. Note: I tried successful serialization and de-serialization using NewtonSoft. but I do not want a dependency of my Web API Client on NetwonSoft, as I am already using RestSharp.


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

JsonSerializer to use Newtonsoft.Json instead of SimpleJson · Issue , I've serialized by DataContractJsonSerializer (System.Runtime.Serialization.Json​;) class Class1 with property Prop1 with alternative name for  I'm having a problem with RestSharp deserializing the return content into my classes. From all my searching it seems that I am doing this correctly. I would much rather use RestSharp's deserializer than have to fall back to another package like Newstonsoft's Json.NET.


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.

Working around the Json Serializer in RestSharp's RestClient : csharp, restsharp / RestSharp Json's attributes and most of the class is not actually implemented, with the JsonSerializer not recognizing the SerializeAs attribute (​as is noted when we used the JsonConvert class to serialize our objects instead that would cause existing functionality to not work as expected)  We do not plan to fix or add new features to the default JSON serializer, since it handles a lot of cases already and when you need to handle more complex objects, please consider using alternative JSON serializers mentioned below. You can use either the default XML serializer or the DotNetXmlSerializer, which uses System.Xml.Serialization


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));
    }

Swagger create JSON result .NET - .net - iOS, I had issues is my tests when using RestSharp's RestClient to send Json. the serializer but its not done: https://github.com/restsharp/RestSharp/pull/1073 Set the Serializer on the RestRequest object using 'JsonSerializer' property then What are some examples of tasks given to them, and what is expected from them​? using System.Text.Json; using System.Text.Json.Serialization; Attributes from the System.Runtime.Serialization namespace aren't currently supported in System.Text.Json. How to write .NET objects to JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer.Serialize method. The following example creates JSON as a string:


Visual Basic .NET Language Knowledge Base, 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​  When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized. For example, you can use this attribute to prevent the serialization of sensitive data.


Restsharp camelcase, 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​  An issue I and my team had been running into was with the JsonSerializer not recognizing the SerializeAs attribute (as is noted in the summary documentation above the JsonSerializer class) but also not recognizing the JsonProperty attribute from Newtonsoft and I could not find any references to Newtonsoft in the project dependencies.


However, my objects property names does not match those expected I read that adding SerializeAs attribute (with a Name specified) on my  [ Natty] .net RestSharp serialization to JSON, object is not using SerializeAs attribute as expected By: Jigar Patel 0.5; [ Natty ] google-cloud-composer Composer auto scaling? By: Joshua H 1.5 ;