Home > database >  How to set variable data in JSON body for the code that generated by Postman in c#
How to set variable data in JSON body for the code that generated by Postman in c#

Time:11-22

    var client = new RestClient("https://azuretitanicapp.azurewebsites.net/predict");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic PEJhc2ljIEF1dGggVXNlcm5hbWU OjxCYXNpYyBBdXRoIFBhc3N3b3JkPg==");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "ARRAffinity=a6e48b9e9d2653435be7b61998d8624b44115214104213d6c8b8c526cc56dc70; ARRAffinitySameSite=a6e48b9e9d2653435be7b61998d8624b44115214104213d6c8b8c526cc56dc70");
var body = @"{
"   "\n"  
@"    ""Pclass"": ""2"",
"   "\n"  
@"    ""Age"": ""55""
"   "\n"  
@"}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

This is the code and here I want to set age=72 as a variable. For example

int variable_age= 72;

in JSON body, it should be like this

age : variable_age

Please help me, I'm having a hard time for figuring it out.

CodePudding user response:

Try use string interpolation. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

int variable_age= 72;
var body = @"{
"   "\n"  
@"    ""Pclass"": ""2"",
"   "\n"  
@"    ""Age"": ""{variable_age}""
"   "\n"  
@"}";

CodePudding user response:

try like this.

https://restsharp.dev/usage/parameters.html#url-segment

Class

public class BodyJson
{
  public int Pclass {get;set;}
  public int Age    {get;set;}
}

Method

    var param = new BodyJson{Pclass =1 , Age = 55};
    request.AddJsonBody(param);
    var response = client.Execute(request);
  • Related