How to get a JSON string from URL?

286,225

Solution 1

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

Solution 2

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
}

Solution 3

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
}
Share:
286,225

Related videos on Youtube

ThdK
Author by

ThdK

Web developer and photographer

Updated on April 02, 2021

Comments

  • ThdK
    ThdK about 3 years

    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.

  • Waihon Yew
    Waihon Yew about 13 years
    @jsmith: It wasn't a suggestion... the OP mentioned it :)
  • ThdK
    ThdK about 13 years
    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! :)
  • Skuli
    Skuli almost 10 years
    Why do you skip the using statement that is used in the answer from Jon?
  • Si8
    Si8 almost 6 years
    You have to use it in a Task with async
  • Alex Jolig
    Alex Jolig about 5 years
    It didn't work for me until I put var json = wc.DownloadString("url"); in try-catch block!
  • Uthen
    Uthen over 4 years
    I found error "HttpRequestException: Cannot assign requested address".. this is URL : "localhost:5200/testapi/swagger/v1/swagger.json, but it's worked with URL : petstore.swagger.io/v2/swagger.json
  • MBentley
    MBentley almost 2 years
    WebClient is now obsolete and you should use httpClient.GetStringAsync as shown below by Richard Garside.