Search code examples
.netjsonserializationrestsharp

Property mapping in RestSharp for JSON doesn't work


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


Solution

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