Question

I'm working on this project that needs to serialize JSON objects to post parameters using RestSharp, below is my code:

        var request = new RestRequest();
        request.Method = Method.POST;
        request.RequestFormat = DataFormat.Json;

        request.AddBody(jsonObject);
        return client.Execute<dynamic>(request);

What I realize is instead of adding each JSON name value pair as a post parameter, request.AddBody adds the whole JSON string as one large post parameter. My question is, is there any way to cause request.AddBody method to add each JSON name-value pair as individual post parameters? I know that request.AddParameter() does the job but that requires manual effort to add each parameter.

Instead of:

     [0]:{
           application/json="
           {
               "name":"john doe",
               "age": "12",
               "gender": "male"}
           }
         }

Desired Result:

     [0]:"name":"john doe"
     [1]:"age":"12"
     [2]:"gender":"male"
Était-ce utile?

La solution

The answer would seem to be to iterate through your jsonObject and turn each desired JSON name-value pair into a parameter. To do this you can use the request.AddParameter method in a loop which iterates through the name-value pairs of your jsonObject with something like:

foreach (var pair in jsonObject) 
{ 
    request.AddParameter(pair.Key, pair.Value); 
}

This is probably oversimplified, but using a library like JSON.NET, it should be quite easy to do. Then you can wrap this functionality into a nice little method somewhere and reuse at will. No manual labour.

NB: You probably want to remove the line request.RequestFormat = DataFormat.Json in your existing code, since JSON is exactly what you don't appear to want to POST.

Autres conseils

request.AddObject(jsonObject)

should do what you expect

Quote from RestSharp docs:

To add all properties for an object as parameters, use AddObject().

Had a similar question and found this thread. Came up with a simple approach that I thought I would share in case it would help others.

The trick is to use anonymous objects along with AddJsonBody().

request.AddJsonBody(new { name = "john doe", age = "12", gender = "male" });

RestSharp will automatically serialize the anonymous object into the desired JSON...

{
    "name":"john doe",
    "age": "12",
    "gender": "male"
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top