Send a JSON payload in C# using newtonsoft JSON package

To send and recieve JSON using C# in visual studio, you must install the NuGET package : Newtonsoft Json. Then you can use it to send a payload:

 

// set the text that will be the  json payload as a variable.
var TestJsonMessage = new { id = "8", text = "This is a test of the Newtonsoft package", sentDate = System.DateTime.Now };

// use a web client object
using (WebClient client = new WebClient())
            {
                // convert the variable into JSON
                var dataString = JsonConvert.SerializeObject(TestJsonMessage);
                 // add the content type headers !! super important 
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

             // set a string to recieve the response, and send the payload to an api
               string theresponse =
                client.UploadString("http://someapiaddress", "POST", dataString);

                // display the response on the page for debugging.
                LabelResponse.Text = theresponse;
            }

 

 

Leave a Reply