C# 对象来解决RestSharp中的JSON问题
我正在使用的RESTAPI有一个名为API Key的新字段。这不是一个有效的C#字段名,因此我想知道是否有其他构建主体的方法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
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
,据我所知,它不支持更改序列化行为的属性,因此我将:
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变量无效)
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是一个非常棒的库,可用于此应用程序中,因此我真的希望有一种方法可以解决此问题。非常有效,谢谢。