Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to parse JSON in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 12.9k
    Comment on it

    "Parsing Json in C#"

        Now a days JSON is the most popularly used data exchange format due to its simplicity and light weight, therefore we will see how to hit the API and then parse the received JSON in C#.

    Please go through the following example:

    public DataSet ApiCall(int categoryId)
            {
                DataSet ds = null;
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings.Get("APIURL"));
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync(string.Format("api/solar/GetSubCategories?CategoryId={0}", CategoryId)).Result;
                if (response.IsSuccessStatusCode)
                {
                    var json = response.Content.ReadAsAsync<dynamic>().Result;
                    ds = JsonConvert.DeserializeObject<DataSet>(json);
                    return ds;               
                }
                return null;
    
            }
    

    Note:-> These are the dlls to be referenced for parsing: System.Net.Http,System.Net.Http.Headers, Newtonsoft.Json;

        In this above example we are hitting the method GetSubCategories of an API and passing the parameter CategoryId in the URL. On recieving the successful responce from the API the responce is read into an object "json" by the code line

    var json = response.Content.ReadAsAsync<dynamic>().Result;
    

    This json object is then deserialized into DataSet object:

    ds = JsonConvert.DeserializeObject<DataSet>(json);
    

    Instead of taking dataset we can also create our own class as per the JSON . Following is a site where you can paste your JSON and you will get its corresponding class. JSON TO CLASS

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: