调用AccuWeather邮政编码查询接口JSON反序列化到Location类报错咨询
错误原因
你遇到的报错核心是JSON结构和反序列化目标类型不匹配:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ConsoleAppTest01.Location' because the type requires a JSON object
你调用的AccuWeather邮编查询接口返回的根节点本身就是Locality类型的JSON数组,没有外层对象包裹,但你代码里指定的反序列化目标是自定义的Location类(这是一个JSON对象结构,内部才封装了数组),二者结构完全不匹配,因此反序列化失败。你定义的Location类属于多余的外层封装,和接口实际返回结构不符。
解决方法
- 直接删除无用的
Location类,不需要额外做这层封装 - 将反序列化的目标类型改为
Locality[]或者List<Locality>即可
修改后的Main方法代码
static void Main(string[] args) { string apiUrl = $"http://dataservice.accuweather.com"; Console.Write("Enter ZipCode: "); string zip = Console.ReadLine(); string locationUri = $"{apiUrl}/locations/v1/postalcodes/search?apikey={APIKEY}&q={zip}"; // 仅需修改泛型参数为Locality数组类型即可 Locality[] locationData = GetLocation<Locality[]>(locationUri); }
可选优化:兼容异常场景
可以在反序列化逻辑中增加判空逻辑,避免接口返回空内容时触发报错:
protected static T GetLocation<T>(string uri) { T result; HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; request.Method = "GET"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string jsonString = reader.ReadToEnd(); // 增加空内容校验 if(string.IsNullOrWhiteSpace(jsonString)) { return default(T); } result = JsonConvert.DeserializeObject<T>(jsonString); } return result; }
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

