6

I have such code:

using System;
using RestSharp.Serializers;

public class Program
{
    public static void Main()
    {
        var obj = new Order();
        obj.Test = 42;
        var serializer = new JsonSerializer();
        var json = serializer.Serialize(obj);
        Console.WriteLine(json);    
    }
}

public class Order
{
    [SerializeAs(Name = "object")]
    public string Object
    {
        get { return "Order"; }
    }

    [SerializeAs(Name = "TestName")]
    public int Test
    {
        get;set;
    }           
}

Based on SerializeAs attribute, RestSharp should use names from attribute, not the property name. But it just ignores it. Output for this code is:

{
  "Object": "Order",
  "Test": 42
}

Am I missed something or it doesn't work with RestSharp?

The same code snippet in DotNetFiddle - http://dotnetfiddle.net/ffaXUY

2
  • Does this even compile? Object is a reserved keyword Feb 28, 2014 at 16:41
  • We can use class names as Property names. It's ok. But if I would use object, then it won't compile Feb 28, 2014 at 16:41

2 Answers 2

3

According to this resource:

RestSharp has decided to bring back Newtonsoft.JSON support in v107.0.

So, if you are using a RestSharp 107+, you can safely use JsonPropertyAttribute attribute to specify property mapping. This is especially useful when dealing with APIs using another naming convention (e.g. snake case).

Related.

1
  • hm, yeah. that's interesting. I'll accept this answer as it's more up to date information. Thanks! Apr 30, 2019 at 14:04
3

Well, RestSharp uses SimpleJson, that hasn't any reference to SerializeAs and it also hasn't own mechanism for it. I found a pull request - https://github.com/restsharp/RestSharp/pull/331 , but it was closed because of SimpleJson.

In default implementation of IJsonSerializerStrategy - PocoJsonSerializerStrategy there is some initial logic to do property name replacing, but it doesn't work for now. It has such method - https://github.com/facebook-csharp-sdk/simple-json/blob/master/src/SimpleJson/SimpleJson.cs:

protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)
{
    return clrPropertyName;
}

So i just replaced SimpleJson to Newtonsoft Json based on the sample from this article - http://blog.patrickmriley.net/2014/02/restsharp-using-jsonnet-serializer.html

2
  • But it doesn't work for deserializing. How can I get such behaviour with response data?
    – Neshta
    Sep 3, 2015 at 11:30
  • RestSharp is using Newtonsoft Json.Net for a while. See my answer. Apr 30, 2019 at 10:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.