OpenWeather地理编码API反序列化报错及经纬度转字符串求助
解决OpenWeather地理编码API反序列化问题
1. 核心问题定位
OpenWeather地理编码API返回的是JSON数组(格式类似 [{"lat": 39.9042, "lon": 116.4074, ...}, ...]),而你之前的代码应该是尝试直接反序列化成单个Weathermap对象,类型不匹配导致了异常。
2. 修正实体类字段映射
API返回的字段是小写的lat和lon,需要确保你的Weathermap类属性和JSON字段正确映射,避免因大小写不匹配导致反序列化失败:
使用System.Text.Json(.NET Core/.NET 5+ 默认)
using System.Text.Json.Serialization; public class Weathermap { [JsonPropertyName("lat")] public string Lat { get; set; } [JsonPropertyName("lon")] public string Lon { get; set; } }
使用Newtonsoft.Json(旧项目常用)
using Newtonsoft.Json; public class Weathermap { [JsonProperty("lat")] public string Lat { get; set; } [JsonProperty("lon")] public string Lon { get; set; } }
3. 正确执行反序列化
将JSON字符串反序列化为List<Weathermap>或Weathermap[]类型,再取出目标经纬度:
System.Text.Json 示例
using System.Text.Json; // 假设jsonResponse是API返回的JSON字符串 var locationList = JsonSerializer.Deserialize<List<Weathermap>>(jsonResponse); // 取第一个匹配结果(城市名查询通常第一个就是目标地点) if (locationList != null && locationList.Count > 0) { string targetLat = locationList[0].Lat; string targetLon = locationList[0].Lon; // 后续用这两个字符串做业务开发 }
Newtonsoft.Json 示例
using Newtonsoft.Json; var locationList = JsonConvert.DeserializeObject<List<Weathermap>>(jsonResponse); if (locationList != null && locationList.Count > 0) { string targetLat = locationList[0].Lat; string targetLon = locationList[0].Lon; // 后续逻辑处理 }
4. 额外注意点
- API返回的
lat/lon是数值类型,序列化器会自动将其转换为字符串赋值给你的属性,无需手动转换。 - 必须判断列表是否为空,避免出现索引越界异常。
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

