157

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
  • 18,131
  • 10
  • 32
  • 49
ThdK
  • 8,559
  • 23
  • 69
  • 96

3 Answers3

285

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,724
  • 2
  • 29
  • 44
Zebi
  • 8,444
  • 1
  • 34
  • 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! – Alex Jolig 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
107

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
  • 413,451
  • 75
  • 717
  • 787
  • 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
50

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
  • 85,699
  • 10
  • 79
  • 86