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
}
Related videos on Youtube
Comments
-
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 about 13 years@jsmith: It wasn't a suggestion... the OP mentioned it :)
-
ThdK about 13 yearsThx 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 almost 10 yearsWhy do you skip the using statement that is used in the answer from Jon?
-
Si8 almost 6 yearsYou have to use it in a
Task
withasync
-
Alex Jolig about 5 yearsIt didn't work for me until I put
var json = wc.DownloadString("url");
intry-catch
block! -
Uthen over 4 yearsI 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 almost 2 yearsWebClient is now obsolete and you should use httpClient.GetStringAsync as shown below by Richard Garside.