Search code examples
c#restapipostrestsharp

How to POST many different field names in RestSharp?


how I can POST many different field names in RestSharp? Below is the code I have tried , will it be like this or other way. Any help here will be appreciated.

JObject jsonPOST = new JObject();

jsonPOST.Add("VariableName1", "temp1" );

jsonPOST.Add("VariableName2", "temp2" );



JObject jsonPOST1 = new JObject();

jsonPOST1.Add("VariableName1", "temp1" );

jsonPOST1.Add("VariableName2", "temp2" );


JObject jsonPOST2 = new JObject();

jsonPOST1.Add("number1", "2" );

jsonPOST1.Add("number2", "4" );

restRequest.AddParameter("application/json", jsonPOST , ParameterType.RequestBody);
restRequest.AddParameter("application/json", jsonPOST1 , ParameterType.RequestBody);
restRequest.AddParameter("application/json", jsonPOST2 , ParameterType.RequestBody);

how to POST the data like this with the above RestSharp structure??

I want this format the POST Request that will be sent to the REST Api.

"{

"FieldName1":{

"VariableName1": "temp1",

"VariableName2": "temp2",

},

"FieldName2":{

"VariableName1": "temp1",

"VariableName2": "temp2",

},

"FieldName3": {

"number1": "2",

"number2": "4",

}

}"

Solution

  • You need to combine all your JObject on one JObject.

    // Main JObject
    var mainObj = new JObject();
    
    // Syntax i love
    var obj1 = new JObject
    {
        {"name", "CorrM"},
        {"ip", "127.0.0.1"}
    };
    
    // Syntax are accepted too
    var obj2 = new JObject();
    obj2.Add("bla1", "bla");
    obj2.Add("bla2", "bla");
    
    // Combine on one JObject
    mainObj.Add("FieldName1", obj1);
    mainObj.Add("FieldName2", obj2);
    

    Then add to body (Convert to string). (i don't know that the correct way to set the Body or not)

    restRequest.AddParameter("application/json", mainObj.ToString(Formatting.None), ParameterType.RequestBody);
    

    Output string must looks like that

    {
      "FieldName1": {
        "name": "CorrM",
        "ip": "127.0.0.1"
      },
      "FieldName2": {
        "bla1": "bla",
        "bla2": "bla"
      }
    }