سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top