166

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.

3 Answers 3

292

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");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why do you skip the using statement that is used in the answer from Jon?
It didn't work for me until I put var json = wc.DownloadString("url"); in try-catch block!
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
WebClient is now obsolete and you should use httpClient.GetStringAsync as shown below by Richard Garside.
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
}

2 Comments

@jsmith: It wasn't a suggestion... the OP mentioned it :)
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! :)
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
}

1 Comment

You have to use it in a Task with async

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.