Thursday, August 8, 2013

C# Working With JSON Web Service

string serviceUrl = ConfigurationManager.AppSettings["serviceUrl"].ToString();
var httpWebRequest = (HttpWebRequest)WebRequest.Create(serviceUrl );
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.Accept = "application/json";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
string json = "auth_token=" + token; // Not actually JSON format (effectively a simple query string)
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
var result = streamReader.ReadToEnd(); // data in JSON format
// Parse the JSON into custom object
 JavaScriptSerializer serializer1 = new JavaScriptSerializer();
customClass obje = serializer1.Deserialize<customClass>(result); 


In the above example the web service outputs JSON, but takes data in via query string. The code could be adapted to send the data in as JSON as well.

No comments:

Post a Comment