如何在C#中访问JSON对象的结果

时间:2019-02-22 11:33:40

标签: c# json

如何通过C#Rest API调用遍历JSON结果:

        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?

            }
        }

resp对象中没有“数据”:

Showing resp object

Visual Studio似乎未在“ resp”中显示任何结果-但我知道它们在那里,因为我在邮递员中看到过结果。

谢谢,马克

3 个答案:

答案 0 :(得分:3)

GetResponseStream()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);
    }
}

有关GetResponseStream的更多信息

有关StreamReader的更多信息

有关JsonConvert的更多信息

依赖项:Newtonsoft.Json

答案 1 :(得分:2)

使用HttpWebResponse.GetResponseStream方法以Stream的形式获取结果。然后,您可以使用Newtonsoft JSON.NET来解析结果。

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
            }

        }
    }

答案 2 :(得分:0)

动态dynJson = JsonConvert.DeserializeObject(response);