Reputation:
I just started programming. What is a simple way to grab the temperature and display it on screen? I want to write a simple program.
static void Main()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://api.openweathermap.org");
var response = client.GetAsync($"/data/2.5/weather?q=London,UK&appid={APIKey}&units=metric");
// What do I place here??
Console.WriteLine(Main.Temp);
}
Upvotes: 0
Views: 2057
Reputation:
Using answer from John:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static async Task Main()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://api.openweathermap.org");
var response = await client.GetAsync($"/data/2.5/weather?q=London,UK&appid={APIKey}");
// This line gives me error
var stringResult = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<dynamic>(stringResult);
var tmpDegreesF = Math.Round(((float)obj.main.temp * 9 / 5 - 459.67),2) ;
Console.WriteLine($"Current temperature is {tmpDegreesF}°F");
Console.ReadKey();
}
}
}
Locate something similar to netcoreapp2.1 Under this line, add 7.1 - this will instruct VS and the compiler to check your code/compile your code against C# 7.1 rules
Update: What I read also from above, I can either create JSON classes to represent data (the easiest way is to use the Edit | Paste Special menu), or deserialize to dynamic.
Upvotes: 0
Reputation: 71
There are 2 concepts you need to consider here:
HttpClient.GetAsync()
is an asynchronous method. There is a nice walk-through of working with async APIs in Microsoft's documentation.
But the gist of it is that method doesn't return the data from the endpoint. It returns a "promise"; something that represents the data that will be available at a future time. Since your program isn't doing any other things, you can just await
the result, like so:
var response = await client.GetAsync();
But of course, you need to first make the enclosing method async
. In your case, change the signature of your Main()
function to:
static async Task Main(string[] args)
The endpoint you're calling returns its data in JSON format. Since you're just learning, I wouldn't bother trying to find an actual schema or client library.
What you should do instead is to create a class with properties for each of the fields in the response, and deserialize into it, as shown here: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Upvotes: 3