Trying to call a weather API using a service for asp.net mvc.
I have a Weather class that looks like this:
public class Weather
{
public string main { get; set; }
public string description { get; set; }
}
The method I am using to make the GET request looks like this:
async public static Task<List<Weather>> GetWeather()
{
List<Weather> weatherData = new List<Weather>();
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&APPID=[MYKEY]");
HttpContent content = response.Content;
string data = await content.ReadAsStringAsync();
}
The URI I'm requesting returns JSON objects.
{
"coord": {
"lon": 139,
"lat": 35
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"base": "stations",
"main": {
"temp": 299.26,
"pressure": 1007,
"humidity": 83,
"temp_min": 296.15,
"temp_max": 301.15
},
"visibility": 16093,
"wind": {
"speed": 5.1,
"deg": 330,
"gust": 7.2
},
"clouds": {
"all": 90
},
"dt": 1533638820,
"sys": {
"type": 1,
"id": 7618,
"message": 0.0028,
"country": "JP",
"sunrise": 1533585473,
"sunset": 1533634868
},
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
I want to access the "weather" object and extract the properties main and description and in my GetWeather return a list where the weather properties from the JSON object match the properties in my class Weather.
I'm lost on what to do with the string data and how to get the JSON data into my List<Weather>.
EDIT
Tried to use JObject.Parse() as mentioned in the answer below but get an error Cannot perform runtime binding on a null reference when trying to print it to the console.
async public static Task<List<Weather>> GetWeather()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&APPID=[MYKEY]");
HttpContent content = response.Content;
string data = await content.ReadAsStringAsync();
dynamic d = JObject.Parse(data);
var main = d.main.ToString();
var description = d.description.ToString();
var weatherData = new List<Weather>
{
new Weather { Main = main,
Description = description }
};
Console.WriteLine(weatherData);
return weatherData;
}