C# Post JSON to HTTP

Basically, in this example we are going to post a Name,Surname,Phone and Email data in JSON form. Then we will get our data as response and deserialize to object from JSON. Finally we will print name value which we send first.

Firstly, we need to install Newtonsoft.Json package using nuget. Follow instructions on https://www.newtonsoft.com/json In this example i am going to use Person Class to serialize our object.

public class Person
        public Person()
        public string name { get; set; }
        public string surname { get; set; }
        public string phone { get; set; }
        public string email { get; set;}     

We are sending our JSON to http page then we are getting response and printing name value in it.

  System.Net.WebRequest request = System.Net.WebRequest.Create("http://YOUR_URL/your_page.php");
            request.Method = "POST";
            Person person = new Person();
            person.name = "John";
            person.surname = "Doe";
            person.phone = "+1234567";
            person.email = "johnexample@examplemail.com";
            String myjson = "data=" +
 //Serializing object

            byte[] byteArray = Encoding.UTF8.GetBytes(myjson);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            System.IO.Stream dataStream = request.GetRequestStream();          
            dataStream.Write(byteArray, 0, byteArray.Length);
            System.Net.WebResponse response = request.GetResponse(); 

            using (dataStream = response.GetResponseStream())
                System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
//Deserializing Response
                Person p = Newtonsoft.Json.JsonConvert.DeserializeObject< Person>(responseFromServer);


Just a page to receive our data and serve it back as response.



echo $_POST['data'];