Cod*_*ker 0 c# post json restsharp web-api-testing
我正在使用 RestSharp 发出包含 JSON 正文的 POST 请求。但我收到错误请求错误。
因为我已经[]在""JSON 中决定使用 Newtonsoft.Json 。在使用它之前,我什至看不到正在形成的 JSON 请求。
我愿意尝试MS httpwebrequest作为替代方案。
restClient = new RestClient();
restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);
var myObject = "{ \"target\" : \"[5,5]\", \"lastseen\" : \"1555459984\" }";
var json = JsonConvert.SerializeObject(myObject);
restRequest.AddParameter("application/json", ParameterType.RequestBody);
restRequest.AddJsonBody(json);
Run Code Online (Sandbox Code Playgroud)
请注意,我正在尝试将 JSON 卷曲转换为 C#。请看下面:
curl -H 'Content-Type: application/json' -X POST -d '{ "target" : [5, 5], "lastseen" : "1555459984", "previousTargets" : [ [1, 0], [2, 2], [2, 3] ] }' http://santized/santized/santized
您似乎过度序列化要发送的数据。
考虑创建一个对象,然后将其传递给AddJsonBody.
//...
restClient = new RestClient();
restRequest = new RestRequest(ApiUrl, Method.POST, DataFormat.Json);
var myObject = new {
target = new []{ 5, 5 },
lastseen = "1555459984",
previousTargets = new []{
new [] { 1, 0 },
new [] { 2, 2 },
new [] { 2, 3 }
}
};
restRequest.AddJsonBody(myObject); //this will serialize the object and set header
//...
Run Code Online (Sandbox Code Playgroud)
AddJsonBody将内容类型设置为application/jsonJSON 字符串并将对象序列化为 JSON 字符串。
| 归档时间: |
|
| 查看次数: |
9754 次 |
| 最近记录: |