Making a JSON service request using C#
- November 11th, 2009
- Posted in Tech Recipes . WCF
- By Germán Medina
- Write comment
This is an easy way to make a JSON POST request to a remote service using C#:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json; charset=utf-8"; DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType()); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, data); String json = Encoding.UTF8.GetString(ms.ToArray()); StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(json); writer.Close();
Notice that in line 4 we create an instance of DataContractJsonSerializer (Assembly: System.ServiceModel.Web) and initialize it with the type of object we are serializing as JSON to send to the service. In lines 5 and 6 the serializer writes the object into a Stream. Line 7 transforms the Stream into an UTF-8 String (as the content-type) and finally in lines 8 to 10 we send the data to the service.
The “data” variable defined in where? What is the type?
The data variable should be any class you are trying to serialize to send to the JSON service.