如何使用 restsharp post 复杂 Json 数据(正文)?

How to post complex Json data (body) using restsharp?

希望你一切顺利!!

我需要使用 restsharp 做一个 post 请求,下面给出了要添加到请求中的正文。这比我之前做的 post 请求有点复杂。

我请求帮助的复杂 Post:

{
  "contextInfoId": "string",
  "userId": "string",
  "specificOs": "string",
  "buildPlatform": "string",
  "deviceName": "string",
  "deviceId": "string",
  "token": "string",
  "loginInfo": {
    "loginInfoId": "string",
    "loginDate": "2019-03-14T06:21:39.693Z"
  }
}

这个问题对我来说是'loginInfo:'必须提供的方式

我已使用以下代码添加基本 post 正文以请求:

//Add json data/body
request.AddJsonBody(new { buProfileId ="1", divisionNames = "IDC", businessUnitNames = "XYZ", processGroupNames = "ABC", systemOrProjectName = "Test", customername = "User" });

上面的 C# 代码适用于如下所示的主体。

{
  "buProfileId": "string",
  "divisionNames": "string",
  "businessUnitNames": "string",
  "processGroupNames": "string",
  "systemOrProjectName": "string",
  "customername": "string"
}

谁能告诉我如何实现复杂的 post 操作。

您可以创建一个 json 对象并为其赋值,然后您可以序列化 json 并在正文中发送

public class LoginInfo
{
    public string loginInfoId { get; set; }
    public DateTime loginDate { get; set; }
}

public class Context
{
    public string contextInfoId { get; set; }
    public string userId { get; set; }
    public string specificOs { get; set; }
    public string buildPlatform { get; set; }
    public string deviceName { get; set; }
    public string deviceId { get; set; }
    public string token { get; set; }
    public LoginInfo loginInfo { get; set; }
}

public IRestResponse Post_New_RequestType(string context, string user_ID, string Specific_Os, string Build_Platfrom, string Device_Name, string device_Id, string Token_Value, string login_infoId, DateTime Login_Date)
        {

            Context tmp = new Context();
            tmp.contextInfoId = context;
            tmp.userId = user_ID;
            tmp.specificOs = Specific_Os;
            tmp.buildPlatform = Build_Platfrom;
            tmp.deviceName = Device_Name;
            tmp.deviceId = device_Id;
            tmp.token = Token_Value;
            tmp.loginInfo.loginInfoId  = login_infoId;
            tmp.loginInfo.loginDate = Login_Date;


            string json = JsonConvert.SerializeObject(tmp);
            var Client = new RestClient(HostUrl);
            var request = new RestRequest(Method.POST);
            request.Resource = string.Format("/api/example");
            request.AddParameter("application/json", json, ParameterType.RequestBody);
            IRestResponse response = Client.Execute(request);
            return response;
}