Wednesday, November 19, 2014

Reading JSON data from a webservice


Create a class for the JSON data

public class JSONData
{
public string id{ get; set; }
public string name{ get; set; }
}

Use this to consume the webservice

string requestURL = "Webservice URL";
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(requestURL), "NTLM", CredentialCache.DefaultNetworkCredentials);
HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(requestURL);
spRequest.Credentials = credCache;
spRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
spRequest.Method = "GET";
spRequest.Accept = "application/json;odata=verbose";
HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();
if (endpointResponse.StatusCode == HttpStatusCode.OK)
{
                using (endpointResponse)
{
using (var reader = new StreamReader(endpointResponse.GetResponseStream()))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
string jSON = reader.ReadToEnd();
JSONData data = new JavaScriptSerializer().Deserialize<JSONData>(jSON);
string strId = data.id;
string strName=data.name;
}
catch (Exception ex)
{
throw ex;
}
}
}
}

No comments:

Post a Comment