163

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.

Syscall
  • 19,327
  • 10
  • 37
  • 52
ThdK
  • 9,916
  • 23
  • 74
  • 101

3 Answers3

287

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");
}
Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
Zebi
  • 8,682
  • 1
  • 36
  • 42
  • 8
    Why do you skip the using statement that is used in the answer from Jon? – Skuli May 30 '14 at 09:03
  • 1
    It didn't work for me until I put `var json = wc.DownloadString("url");` in `try-catch` block! – Ghasem Apr 17 '19 at 06:40
  • I found error "HttpRequestException: Cannot assign requested address".. this is URL : "http://localhost:5200/testapi/swagger/v1/swagger.json, but it's worked with URL : https://petstore.swagger.io/v2/swagger.json – Uthen Aug 30 '19 at 08:52
  • 3
    WebClient is now obsolete and you should use httpClient.GetStringAsync as shown below by Richard Garside. – MBentley Jun 20 '22 at 15:55
109

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
}
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 1
    @jsmith: It wasn't a suggestion... the OP mentioned it :) – Jon Apr 06 '11 at 13:28
  • Thx for helping me out, It's strange that i didn't find this on google, this realy was a basic question isn't it? I'm now having an error like: Cannot deserialize JSON object into type 'System.String'. I know that it is some attribute in my class that is not right declared, but i just can't find wich one. But i'm still trying! :) – ThdK Apr 06 '11 at 14:07
56

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
}
Richard Garside
  • 87,839
  • 11
  • 80
  • 93