简体   繁体   中英

Net Core Simple way to Find Temperature from Openweather API

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


}

There are 2 concepts you need to consider here:

Asynchronous programming

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)

JSON Deserialization

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

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=c44d8aa0c5e588db11ac6191c0bc6a60");

            // 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM