-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIWeatherSource.cs
More file actions
52 lines (33 loc) · 1.56 KB
/
APIWeatherSource.cs
File metadata and controls
52 lines (33 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using Newtonsoft.Json.Linq;
namespace WeatherDataCollector {
//CLASS TO GET WEATHER DATA FROM OpenWeatherAPI
internal class APIWeatherSource : IWeatherDataSource {
public WeatherData SendWeatherData () {
return CreateWeatherData();
}
//GETS THE CURRENT WEATHER THROUGH THE API
public string GetCurrentWeatherData () {
HttpClient client = new HttpClient();
string cityName = "Budapest";
string apiKey = "cdaaf44170dad0a7d8b66513db2f0a9d";
string userURL = $"https://api.openweathermap.org/data/2.5/weather?q={cityName}&appid={apiKey}&units=metric";
//THE RESPONSE ARRIVES IN JSON FORMAT
string? weatherResponse = client.GetStringAsync(userURL).Result;
return weatherResponse;
}
//CREATES WeatherData FROM THE JSON
public WeatherData CreateWeatherData () { //OUT
string weatherDataText = GetCurrentWeatherData();
JObject responseJson = JObject.Parse(weatherDataText);
/*
foreach (JToken property in responseJson.Properties()) {
Console.WriteLine(property);
}*/
//RESPONSE JSON FILE IS NESTED
string description = responseJson["weather"]?[0]?["description"]?.ToString();
double temperature = Convert.ToDouble(responseJson["main"]?["temp"]);
WeatherData newWeatherData = new WeatherData(temperature, description);
return newWeatherData;
}
}
}