反对 RestSharp 中的 JSON 问题

Object to JSON issue in RestSharp

我正在使用的 Rest API 有一个名为 Api-Key 的新字段。这不是一个有效的 C# 字段名称,所以我想知道是否有不同的构建主体的方法。

   var client = new RestClient("https://TestWeb");

        var request = new RestRequest("login", Method.POST);
        request.AddHeader("Content-type", "application/json");

        request.AddJsonBody(
           new {
               credentials =
            new
            {
                username = "Uname",
                password = "password",
                Api-Key = "apikey"
            } }); 

由于 RestSharp 默认使用 Json 序列化器 SimpleJson,据我所知,它不支持改变序列化行为的属性,我会:

  1. 安装为 NuGet 包 Newtonsoft Json,以便使用其 JsonProperty 属性。

  2. 定义一个class来提供这样的认证对象:

    public class AuthenticationInfos
    {
        [JsonProperty(PropertyName = "username")]
        public string Username { get; set; }
    
        [JsonProperty(PropertyName = "password")]
        public string Password { get; set; }
    
        [JsonProperty(PropertyName = "Api-Key")]
        public string ApiKey { get; set; }
    }
    

(关键部分在这里[JsonProperty(PropertyName = "Api-Key")],你告诉序列化器用那个名字序列化那个属性,它作为C#变量是无效的)

  1. 使用Newtonsoft Json序列化对正文请求进行序列化:

    var client = new RestClient("https://TestWeb");
    
    var request = new RestRequest("login", Method.POST);
    request.AddHeader("Content-type", "application/json");
    
    var body = new
    {
        credentials =
            new AuthenticationInfos()
            {
                Username = "Uname",
                Password = "password",
                ApiKey = "myApiKey"
            }
    };
    
    var serializedBody = JsonConvert.SerializeObject(body);
    request.AddParameter("application/json", serializedBody, ParameterType.RequestBody);
    

身材会像:

{
    "credentials":
    {
        "username": "Uname", 
        "password": "password",
        "Api-Key": "myApiKey"
    }
}

当然你在反序列化阶段接收消息时也必须这样做。