Search code examples
c#dictionarydeserializationrestsharp

RestSharp send Dictionary


I've seen how to deserialize a dictionary from the response, but how do you send one?

var d = new Dictionary<string, object> {
    { "foo", "bar" },
    { "bar", 12345 },
    { "jello", new { qux = "fuum", lorem = "ipsum" } }
};

var r = new RestRequest(url, method);
r.AddBody(d); // <-- how?

var response = new RestClient(baseurl).Execute(r);

Solution

  • Ugh...it was something else screwing up my case. As @Chase said, it's pretty simple:

    var c = new RestClient(baseurl);
    var r = new RestRequest(url, Method.POST);  // <-- must specify a Method that has a body
    
    // shorthand
    r.AddJsonBody(dictionary);
    
    // longhand
    r.RequestFormat = DataFormat.Json;
    r.AddBody(d);
    
    var response = c.Execute(r); // <-- confirmed*
    

    Didn't need to wrap the dictionary as another object.

    (*) confirmed that it sent expected JSON with an echo service like Fiddler, or RestSharp's SimpleServer