C#调用天气API如何获取用户指定日期对应的温度数据
问题背景
我正在开发对接天气API获取气象数据的项目,该API返回的JSON结构中,days数组按日期存储每日气象数据,单条记录核心字段包括:
datetime:日期,格式为yyyy-MM-ddtemp:当日平均温度- 其余字段包含最高/最低温、降水、风速、日出日落等气象信息
返回的JSON示例片段如下:
"days":[ {"datetime":"2022-06-11","datetimeEpoch":1654898400,"tempmax":22.0,"tempmin":14.2,"temp":18.3,"precip":0.7,"conditions":"Rain, Partially cloudy"/* 其余字段省略 */}, {"datetime":"2022-06-12","datetimeEpoch":1654984800,"tempmax":21.2,"tempmin":11.1,"temp":16.3,"precip":0.0,"conditions":"Partially cloudy"/* 其余字段省略 */} ]
当前使用C#编写的API请求与解析代码如下:
public string GetWeatherWeek() { var baseURL = "https://weather.visualcrossing.com/VisualCrossingWebServices/"; var client = new HttpClient(); var response = client.GetAsync(baseURL).Result; response.EnsureSuccessStatusCode(); 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; }
现有ReadWeather方法固定读取days数组首个元素的温度值,没有匹配传入的dateInput日期参数,需要修改代码实现按传入日期获取对应温度。
解决方案
核心修改思路
遍历days数组的所有元素,对比每条记录的datetime字段值和传入的日期参数,匹配成功后读取对应temp值即可,同时补充输入校验、资源释放、无匹配数据的异常处理逻辑,避免程序报错。
修改后的完整代码
// 需要提前引入对应命名空间 // using System.Text.Json; // using System.Globalization; public double ReadWeather(string dateInput) { // 先校验传入日期格式是否符合yyyy-MM-dd要求,避免无效查询 if (!DateTime.TryParseExact(dateInput, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) { throw new ArgumentException("输入日期格式不符合要求,请使用yyyy-MM-dd格式"); } var data = GetWeatherWeek(); // 给JsonDocument加using声明,用完自动释放内存 using var json = JsonDocument.Parse(data); var daysArray = json.RootElement.GetProperty("days"); // 遍历days数组匹配目标日期 foreach (var dayItem in daysArray.EnumerateArray()) { var currentDate = dayItem.GetProperty("datetime").GetString(); if (string.Equals(currentDate, dateInput, StringComparison.Ordinal)) { return dayItem.GetProperty("temp").GetDouble(); } } // 遍历完未找到匹配日期时抛出明确异常 throw new KeyNotFoundException($"未找到日期{dateInput}对应的气象数据"); }
注:日期格式校验逻辑需要引入命名空间
using System.Globalization;,JSON解析需要引入using System.Text.Json;
额外优化建议
- 不要每次调用
ReadWeather都发起HTTP请求拉取全周数据,可以把拉取到的天气数据做5-10分钟的短缓存,减少不必要的API调用,避免触发接口限流 HttpClient建议使用全局单例,不要每次调用GetWeatherWeek都新建实例,否则长期运行可能出现套接字耗尽问题- 日期对比时使用Ordinal字符串对比规则,性能更高,也能避免不同区域文化设置导致的格式匹配问题
内容的提问来源于stack exchange,提问作者stackie
相关产品推荐
相关产品推荐

