문제

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