Home > Blockchain >  Get temperature on specific date using weather api
Get temperature on specific date using weather api

Time:06-13

I'm working on a project to get data from a weather API. My JSON looks like this:

"days":[{"datetime":"2022-06-11","datetimeEpoch":1654898400,"tempmax":22.0,"tempmin":14.2,"temp":18.3,"feelslikemax":22.0,"feelslikemin":14.2,"feelslike":18.3,"dew":12.8,"humidity":71.5,"
precip":0.7,"precipprob":100.0,"precipcover":8.33,"preciptype":["rain"],"snow":0.0,"snowdepth":0.0,"windgust":36.0,"windspeed":20.2,"winddir":247.2,"pressure":1021.8,"cloudcover":63.1,"visibility":17.6,"solarradiation":292.0,"solarenergy":25.3,"uvindex":9.0,"severerisk":10.0,"sunrise":"05:15:13","sunriseEpoch":1654917313,"sunset":"21:52:36","sunsetEpoch":1654977156,"moonphase":0.44,"conditions":"Rain, Partially cloudy","description":"Partly cloudy throughout the day with morning rain.","icon":"rain","stations":["EDDL","EHVK","EDLV","EHDL","F2527"],"source":"comb"},
{"datetime":"2022-06-12","datetimeEpoch":1654984800,"tempmax":21.2,"tempmin":11.1,"temp":16.3,"feelslikemax":21.2,"feelslikemin":11.1,"feelslike":16.3,"dew":10.0,"humidity":67.6,
"precip":0.0,"precipprob":4.8,"precipcover":0.0,"preciptype":["rain"],"snow":0.0,"snowdepth":0.0,"windgust":36.4,"windspeed":20.5,"winddir":262.2,"pressure":1022.0,"cloudcover":70.8,"visibility":24.1,"solarradiation":318.5,"solarenergy":27.3,"uvindex":8.0,"severerisk":10.0,"sunrise":"05:14:56","sunriseEpoch":1655003696,"sunset":"21:53:16","sunsetEpoch":1655063596,"moonphase":0.47,"conditions":"Partially cloudy","description":"Partly cloudy throughout the day.","icon":"partly-cloudy-day","stations":null,"source":"fcst"}

My program to get data from api looks like this:

public string GetWeatherWeek()   
{
    var baseURL = "https://weather.visualcrossing.com/VisualCrossingWebServices/";

    var client = new HttpClient();
    var response = client.GetAsync(baseURL).Result;
    response.EnsureSuccessStatusCode();
    //Console.WriteLine(response.Content.ReadAsStringAsync().Result);
    return response.Content.ReadAsStringAsync().Result;
}

public double ReadWeather(string dateInput)
{
    var data = GetWeatherWeek();
    var json = JsonDocument.Parse(data);
    var weather = json.RootElement.GetProperty("days");
    var date = weather[0].GetProperty("datetime");
    var temperature = weather[0].GetProperty("temp").GetDouble();
    return temperature;
}

Now my question is: how can I retrieve the temperature from the date entered by the user?

CodePudding user response:

try this

     using Newtonsoft.Json;

    var days = (JArray)JObject.Parse(data)["days"];

    var searchDate = "2022-06-12";
    double temp = days.Where(d => (string)d["datetime"] == searchDate)
                     .Select(d => (double)d["temp"])
                     .FirstOrDefault(); //16.3
  • Related