Mark Tait
Mark Tait

Reputation: 643

How do I access the results of a JSON object in C#

How can I loop through the JSON results from this C# Rest API call:

        string url = string.Format("https://example.com/api/mytext");
        System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
        req.Method = "GET";
        req.UserAgent = "mykey";
        req.Accept = "text/json";

        using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
        {
            if (resp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                // how do I access the JSON here and loop through it?

            }
        }

There is no "data" in the resp object:

Showing resp object

Visual Studio doesn't seem to show any results in "resp" - but I know they are there, as I've seen results in postman.

Thanks, Mark

Upvotes: 1

Views: 807

Answers (3)

umesh.chape
umesh.chape

Reputation: 3035

dynamic dynJson = JsonConvert.DeserializeObject(response);

Upvotes: 0

Pavel
Pavel

Reputation: 910

Use HttpWebResponse.GetResponseStream method to get the result as a Stream. Then you can use Newtonsoft JSON.NET to parse the result.

using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
    {
        if (resp.StatusCode == System.Net.HttpStatusCode.OK)
        {
            using (var stream = resp.GetResponseStream())
            {
                // Process data with JSON.NET library here
            }

        }
    }

Upvotes: 2

ColinM
ColinM

Reputation: 2681

Use GetResponseStream() with a StreamReader

string url = string.Format("https://example.com/api/mytext");
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "mykey";
req.Accept = "text/json";

using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse())
{
    if (resp.StatusCode == System.Net.HttpStatusCode.OK)
    {
        string contents;
        // how do I access the JSON here and loop through it?
        using(var responseStream = resp.GetResponseStream())
        using(var responseStreamReader = new StreamReader(responseStream))
        {
            contents = responseStreamReader.ReadToEnd();
        }

        var deserializedContent = JsonConvert.DeserializeObject<T>(contents);
    }
}

See more on GetResponseStream

See more on StreamReader

See more on JsonConvert

Dependencies: Newtonsoft.Json

Upvotes: 4

Related Questions