Search code examples
c#jsonfacebooklinq-to-xmlwebclient

How to get a JSON string from URL?


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.


Solution

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