编程语言
首页 > 编程语言> > c# – RestSharp – 如何影响JSON序列化(命名)?

c# – RestSharp – 如何影响JSON序列化(命名)?

作者:互联网

参见英文答案 > RestSharp serialization to JSON, object is not using SerializeAs attribute as expected                                    4个
我正在尝试与REST服务交谈,我正在尝试调用POST方法,我需要在帖子正文中提供一些数据.

我的模型类都很好地设置了这样的东西:

public class MyRequestClass
{
    public string ResellerId { get; set; }
    public string TransactionId { get; set; }
    ... other properties of no interest here ... 
}

我在C#中使用RestSharp来调用我的REST服务:

RestClient _client = new RestClient(someUrl);

var restRequest = new RestRequest("/post-endpoint", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddHeader("Content-Type", "application/json");

restRequest.AddJsonBody(request);   // of type "MyRequestClass"

IRestResponse<MyResponse> response = _client.Execute<MyResponse>(restRequest);

一切似乎都很好 – 没有例外.但该服务响应:

We are experiencing problem in processing your request

当我查看正在发送的请求JSON时,我看到所有属性都是大写拼写:

{ "ResellerId":"123","TransactionId":"456" }

这导致了问题 – 服务以小写形式排除它们:

{ "resellerId":"123","transactionId":"456" }

所以我尝试用属性来装饰我的C#模型类:

public class MyRequestClass
{
    [RestSharp.Serializers.SerializeAs(Name = "resellerId")]
    public string ResellerId { get; set; }

    [RestSharp.Serializers.SerializeAs(Name = "transactionId")]
    public string TransactionId { get; set; }
    ... other properties of no interest here ... 
}

但这似乎没有改变任何东西 – JSON请求窗口具有大写拼写的属性名称,因此调用失败.

如何告诉RestSharp始终在从C#模型类生成的JSON中使用小写属性名?

解决方法:

你不能或你应该将Json.NET添加到RestSharp.

github repo of RestSharp上有一个问题.

标签:json,c,restsharp
来源: https://codeday.me/bug/20190708/1402007.html