Search code examples
c#web-servicesdotnet-httpclient

Extracting data from response.Content.ReadStringASync


I am currently trying to extract data from my Web Service. I managed to get success response from the Web Service using HTTPClient. However, I am unable to extract specific values. For instance, my JSON document read as

{"d":[{"__type":"Info:#website.Model","infoClosingHours":"06:00:00 PM","infoID":1,"infoOpeningDays":"Monday","infoOpeningHours":"09:00:00 AM","infoStatus":"Open"}]}

I want to get the infoOpeningDays, however, I am unable to do it.

I tried using

dynamicObject.GetType().GetProperty("infoOpeningDays").GetValue(dynamicObject, null); 

dynamicObject["infoOpeningDays"]; 

But it kept giving me null.

Here's my code

private async void GetData(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("ip");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            try{
                HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
                if (response.IsSuccessStatusCode)
                {
                    string jsonString = await response.Content.ReadAsStringAsync();
                    dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
                    //string abc = dynamicObject.IEnumerator.[0].IEnumerator.[0].IEnumerator.[0].IEnumerator.[5].Name;
                    string abc = dynamicObject.GetType().GetProperty("infoOpeningDays").GetValue(dynamicObject, null);
                }
            }
            catch
            {

            }

        }

Solution

  • You should access the properties directly from your dynamic object like this:

    dynamic dynamicObject = JsonConvert.DeserializeObject(json);
    string infoClosingHours = dynamicObject.d[0].infoClosingHours;
    

    Or this is the same

    string infoClosingHours = dynamicObject.d[0]["infoClosingHours"];