如何从 URL 获取 JSON 字符串?

发布于 2024-10-30 12:53:53 字数 300 浏览 3 评论 0原文

我正在将代码从 XML 转换为 JSON。

但我找不到如何从给定的 URL 获取 JSON 字符串。

URL 是这样的:“https://api.facebook.com/method/fql.query?query=.....&format=json”

我之前使用过 XDocuments,在那里我可以使用 load 方法:

XDocument doc = XDocument.load("URL");

对于 JSON,此方法等效于什么?我正在使用 JSON.NET。

I'm switching my code form XML to JSON.

But I can't find how to get a JSON string from a given URL.

The URL is something like this: "https://api.facebook.com/method/fql.query?query=.....&format=json"

I used XDocuments before, there I could use the load method:

XDocument doc = XDocument.load("URL");

What is the equivalent of this method for JSON? I'm using JSON.NET.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清醇 2024-11-06 12:53:53

System.Net 中使用 WebClient 类:

var json = new WebClient().DownloadString("url");

请记住,WebClientIDisposable,因此您可能会添加在生产代码中对此使用 using 语句。这看起来像:

using (WebClient wc = new WebClient())
{
   var json = wc.DownloadString("url");
}

Use the WebClient class in System.Net:

var json = new WebClient().DownloadString("url");

Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:

using (WebClient wc = new WebClient())
{
   var json = wc.DownloadString("url");
}
素食主义者 2024-11-06 12:53:53

AFAIK JSON.Net 不提供从 URL 读取的功能。因此,您需要分两步执行此操作:

using (var webClient = new System.Net.WebClient()) {
    var json = webClient.DownloadString(URL);
    // Now parse with JSON.Net
}

AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:

using (var webClient = new System.Net.WebClient()) {
    var json = webClient.DownloadString(URL);
    // Now parse with JSON.Net
}
Saygoodbye 2024-11-06 12:53:53

如果您使用的是 .NET 4.5 并且想要使用异步,那么您可以在 System.Net.Http 中使用 HttpClient

using (var httpClient = new HttpClient())
{
    var json = await httpClient.GetStringAsync("url");

    // Now parse with JSON.Net
}

If you're using .NET 4.5 and want to use async then you can use HttpClient in System.Net.Http:

using (var httpClient = new HttpClient())
{
    var json = await httpClient.GetStringAsync("url");

    // Now parse with JSON.Net
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文