1

I want to send a POST request in c# and i need the following sent through

"jsonrpc": "2.0",
"id": "12345",
"method": "my method",
"params": {
    "api_key": "my api key",
    "preset_id": "my preset id"
}

I tried using

using (WebClient client = new WebClient ())
    {
        byte [] response =
        client.UploadValues ("my url", new NameValueCollection ()
        {
            { "jsonrpc", "2.0" },
            { "id", "12345"},
            { "method", "my method"},
            { "params", ""}
        });
        string result = System.Text.Encoding.UTF8.GetString (response);
    }

But i couldnt make the params an array, Please help, Thank you

  • 1
    Possible duplicate of [POSTing JSON to URL via WebClient in C#](http://stackoverflow.com/questions/15091300/posting-json-to-url-via-webclient-in-c-sharp) – CodingYoshi Dec 31 '16 at 02:38
  • @CodingYoshi Not exactly, my issue comes from the fact that i can have params be an array. And the solution you posted doesnt use arrays either. Thanks for trying – Aleksei ivanov Dec 31 '16 at 02:53

1 Answers1

0

It appears that you are asking for the parameters to be in an array, but they are actually shown as a "subclass". If the values were in an array, they should have square brackets around them.

However, both results are easy to achieve using anonymous (or real) classes (which I much prefer over embedding the property names in quoted text (makes future modifications much easier to implement).

        var parameters = new
                         {
                             api_key = "my api key",
                             preset_id = "my preset id"
                         };

        var json = new
                   {
                       jsonrpc = "2.0",
                       id = "12345",
                       method = "my method",
                       @params = parameters
                   };
        string sResult = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(json);

The above code will result in the same output that you have shown. If you want an actual array instead, you can change the parameters definition to:

        var parameters = new NameValueCollection();
        parameters.Add("api_key", "my api key");
        parameters.Add("preset_id", "my preset id");

Note that I used the .Net framework json serializer (from System.Web.Extensions), but you can use the serializer of your choice (we generally use NewtonSoft's JsonConvert).

competent_tech
  • 44,465
  • 11
  • 90
  • 113