C# GET 请求和解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15219792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:31:30  来源:igfitidea点击:

C# GET Request and Parsing JSON

c#jsongetrequest

提问by Ramesh

I am developing Windows store app in Windows 8, Visual Studio 2012. I need to make GET request to a particular URL and get the JSON as response. And I need to parse the JSON to get the values in it. I need C# code to do the above functionality.

我正在 Windows 8 Visual Studio 2012 中开发 Windows 商店应用程序。我需要向特定 URL 发出 GET 请求并获取 JSON 作为响应。我需要解析 JSON 以获取其中的值。我需要 C# 代码来完成上述功能。

采纳答案by Darin Dimitrov

You can use this sample code from MSDN

您可以使用MSDN 中的此示例代码

    var client = new HttpClient();
        var uri = new Uri("http://ponify.me/stats.php");
        Stream respStream = await client.GetStreamAsync(uri);
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(rootObject));
        rootObject feed = (rootObject)ser.ReadObject(respStream);
        System.Diagnostics.Debug.WriteLine(feed.SONGHISTORY[0].TITLE);

回答by Darin Dimitrov

You could use the HttpClientclass. The GetAsyncmethod allows you to send a GET request to a specified url:

你可以使用这个HttpClient类。该GetAsync方法允许你发送一个GET请求到指定的URL:

public async Task<JsonObject> GetAsync(string uri)
{
    var httpClient = new HttpClient();
    var content = await httpClient.GetStringAsync(uri);
    return await Task.Run(() => JsonObject.Parse(content));
}