How to get a json string from url?

ThdK picture ThdK · Apr 6, 2011 · Viewed 253.1k times · Source

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.

Answer

Zebi picture Zebi · Apr 6, 2011

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");
}