我需要使用具有 JSON 物件陣列作為請求結構的端點。我已經在休息客戶端上對其進行了測驗。問題是我無法在 restsharp 中形成請求正文。
下面是JSON結構
[
{
"id": "1",
"name": "rejected",
"timestamp": "2021-10-07T16:47:37Z",
"identity": "MainId",
"source": "web",
"params": {
"email": "[email protected]",
"fullName": "John Doe",
"Mobile": "444586867857"
}
}
]
我還創建了 POCO 類
public class activityClass
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string id { get; set; }
public string name { get; set; }
public DateTime timestamp { get; set; }
public string identity { get; set; }
public string source { get; set; }
public Params _params { get; set; }
}
public class Params
{
public string email { get; set; }
public string fullName { get; set; }
public string Mobile { get; set; }
}
有呼叫端點的代碼
var client = new RestClient("http://api.tech.com/apiv2");
var request = new RestRequest(Method.POST);
//ThIS IS WHERE THE PROBLEM IS
var body = new activityClass
{
Class1 = new List<Class1>
{
}
}
var json = request.JsonSerializer.Serialize(body);
request.AddParameter("application/json", json, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
uj5u.com熱心網友回復:
我認為你應該像這樣使用序列化物件:
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(body), ParameterType.RequestBody);
您還嘗試使用 request.AddJsonBody() 嗎?
uj5u.com熱心網友回復:
您正在創建的主體不應該基于activityClass物件......相反,基于您的 json,它應該是List<Class1>物件。
你的身體應該看起來像這樣,
var body = new List<Class1> {
new Class1 {
... // this is where your properties are filled in.
},
new Class1 {
...
}
}
只有當您的 json 具有父屬性時,您的實作才會真正起作用,例如,
{
"Property1": [
{
"id": "1",
"name": "rejected",
....
}
]
}
使用 RestSharp .. 你創建你的請求并使用request.AddJsonBody(body)而不是添加引數。應該是這樣的
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
var body = new List<Class1> ...;
request.AddJsonBody(body);
IRestResponse response = client.Execute(request);
uj5u.com熱心網友回復:
如果我試圖自己構建這個呼叫,我會看到一些會給我帶來問題的事情。
- 您正在嘗試序列化 LINQ 物件而不是其中包含的資料
- 根據我的經驗,匿名型別表示法不適用于非字串專案。
- 如果您提供的 JSON 負載示例是目標,那么它的結構并不完全簡單,因為它在 JArray 條目中有一個固定的 JObject。
在代碼中創建 JSON 有效負載時,我從中心開始作業并向外作業。我將從作為“params”值的物件開始。它看起來像下面這樣:
//create our innermost object and fill it
JObject params = new JObject();
params.Add("email", params.email)
params.Add("fullName", params.fullName)
params.Add("Mobile", params.Mobile)
//create the JSON Object that we insert that into and fill the other values
JObject outerBody = new JObject();
outerBody.Add("id", Class1.id)
outerBody.Add("name", Class1.name)
outerBody.Add("timestamp", Class1.timestamp)
outerBody.Add("identity", Class1.identity)
outerBody.Add("source", Class1.source)
outerBody.Add("params", params)
//now finally create the array and insert it
JArray ourArray = new JArray();
ourArray.Add(outerBody);
//once this object is done, you can add this in as a parameter coded as the body:
request.AddParameter("application/json", ourArray, ParemeterType.ReqeustBody);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388867.html
