Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对象来解决RestSharp中的JSON问题_C#_Restsharp - Fatal编程技术网

C# 对象来解决RestSharp中的JSON问题

C# 对象来解决RestSharp中的JSON问题,c#,restsharp,C#,Restsharp,我正在使用的RESTAPI有一个名为API Key的新字段。这不是一个有效的C#字段名,因此我想知道是否有其他构建主体的方法 var client = new RestClient("https://TestWeb"); var request = new RestRequest("login", Method.POST); request.AddHeader("Content-type", "application/json"); re

我正在使用的RESTAPI有一个名为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
,据我所知,它不支持更改序列化行为的属性,因此我将:

  • 安装为NuGet软件包,以便使用其
    JsonProperty
    属性

  • 定义一个类以提供如下身份验证对象:

    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变量无效)

  • 使用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"
        }
    }
    

    当然,在接收消息时,您必须在反序列化阶段使用相同的方法。

    RestSharp是一个非常棒的库,可用于此应用程序中,因此我真的希望有一种方法可以解决此问题。非常有效,谢谢。