如何使用RestSharp发布复杂的JSON数据(body)



我希望你一切都好!

我需要使用RestSharp执行邮政请求,以下要添加要添加到请求的正文。这比我以前做过的帖子请求要复杂。

我请求协助的复杂帖子:

{
  "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:'必须提供的方式

我已经使用以下代码添加了基本的帖子主体:

//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"
}

有人可以让我知道如何实现复杂的后操作。

您可以创建一个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;
}

最新更新