How to Get a JSON String from Url

How to get a JSON string from URL?

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

How to get json string from the url?

C# is provide WebClient class in System.Net get string using this class like

var json = new WebClient().DownloadString("url");

How to get JSON string from URL with Javascript?

As Michael Antonio pointed out, using Ajax would be the way to do it. Heres my code

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function() {
$.ajax({
url: 'http://megarkarsa.com/gpsjson.php',
type: 'GET',
dataType: 'html',
success: function(data, status, xhr)
{
$("#json").html(data);
},
error: function(xhr, status, error)
{
$("#json").html("Error: " + status + " " + error);
}
});
});
</script>
</head>
<body>
<div id="json"></div>
</body>
</html>

However, an error keeps cropping up. Here are the request/response headers, notice the response is force closing the connection.

Request

Host: megarkarsa.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://testsites.kalebklein.com/json1/json.html
Origin: http://testsites.kalebklein.com
Connection: keep-alive

Response

Connection: close
Content-Type: text/html
Date: Mon, 21 Sep 2015 01:52:56 GMT
Server: Apache
Transfer-Encoding: chunked
x-powered-by: PHP/5.4.36

Also notice that the content-type of the response is HTML, and should be JSON if you wish to parse the JSON using the above Ajax function I provided. The error coming back is not helpful whatsoever, meaning that the connection is being cut off or refused by making the Ajax call, and no data is being sent back.

Print JSON string from URL

You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:

function rvOffices() {  $.ajax({    url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',    type: 'GET',    dataType: 'text',    success: function(data) {      var json_result = JSON.parse(data);      //console.log(json_result); // The whole JSON      console.log(json_result.offices[0].name);    }  });}rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to get JSON from URL in JavaScript?

You can use jQuery .getJSON() function:

$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
// JSON result in `data` variable
});

If you don't want to use jQuery you should look at this answer for pure JS solution.

Get Url string parameter as JSON object

In Angular you can get the URL with:

this.router.url

Once you've got the URL, you should use the very popular (14 mill downloads a week) npm qs module:

var qs = require('qs');
var obj = qs.parse('firstName=tom&secondName=Mike');

returns:

{
firstName: 'tom'
secondName: 'mike'
}

how to retrieve JSON data from URL in c#

Your code works. However, you don't try to output result to the console. That's why you don't see anything.

If you add the following to your Main method after the currencyRates, you will see the values that have been retrieved.

Console.WriteLine($"{currencyRates.Disclaimer}");
Console.WriteLine($"{currencyRates.License}");
Console.WriteLine($"{currencyRates.TimeStamp}");
Console.WriteLine($"{currencyRates.Base}");
foreach (var currencyRatesRate in currencyRates.Rates)
{
Console.WriteLine($"Key: {currencyRatesRate.Key}, Value: {currencyRatesRate.Value}");
}

Notes

Generally, it is better you follow standard naming conventions so that the readers of your code can quickly catch up on what is going on. For instance, all method names are written in Pascal Case. Use meaningful naming for your variables. For instance webClient is more meaningful than w. The variable names are written in Camel Case. E.g json_data should be renamed in jsonData.

Avoid having many empty lines in your code. It would be far easier for the reader of your code to focus on a few lines and read your code. Last but not least, you declare a parameter for your method of type string and you never use it. This parameter should be used instead of the hard-coded string in the DownloadString method.

Compare this refactored method with the one we had initially:

private static T DownloadAndDeserializeJsonData<T>(string url) where T : new()
{
using (var webClient = new WebClient())
{
var jsonData = string.Empty;
try
{
jsonData = webClient.DownloadString(url);
}
catch (Exception) { }

return string.IsNullOrEmpty(jsonData)
? new T()
: JsonConvert.DeserializeObject<T>(jsonData);
}
}

If you want a central place for naming guidelines for .NET Framework and C#, you could have a look here.

How to parse Json content from a url with c#?

best way to parse json is Json.NET

string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

I try this code and works:

void Main()
{
var test = Newtonsoft.Json.JsonConvert.DeserializeObject<Test>(getTestObjects().Result).Dump();

// test.MyName; 'Bad Boys'
// test.ReleaseDate; '1995-4-7T00:00:00'
}

public class Test
{
[JsonProperty("Name")]
public String MyName { get; set; }
public String ReleaseDate { get; set; }
}

private string url = "http://bitg.ir/files/json.txt";
private List<Test> TestList = new List<Test>();

private async Task<String> getTestObjects()
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();

return result;
}

how i get JSON as string from url (java)

You can use Spring's RestTemplate to get the response as String, e.g.:

RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("https://www.instagram.com/ihanan95/?__a=1", String.class);
System.out.println(response);

If you are not allowed to use third party libaries then you can do the same with URLConnection, e.g.:

URLConnection connection = new URL("https://www.instagram.com/ihanan95/?__a=1").openConnection();
try(Scanner scanner = new Scanner(connection.getInputStream());){
String response = scanner.useDelimiter("\\A").next();
System.out.println(response);
}


Related Topics



Leave a reply



Submit