You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中JSON反序列化为List类型时出错的解决求助

问题解决:Open-Meteo API反序列化异常修复

错误原因

Open-Meteo API返回的JSON中,hourly_units和hourly是单个JSON对象(格式为{"key":"value"}),但你的模型类中将这两个字段定义为List<>集合类型,导致Json.NET无法将对象反序列化为数组/集合,抛出JsonSerializationException。

解决方案

1. 修正模型类

将WeatherModel中的集合类型改为单个对象类型:

public class WeatherModel
{
    public double latitude { get; set; }
    public double longitude { get; set; }
    public double generationtime_ms { get; set; }
    public double utc_offset_seconds { get; set; }
    public string timezone { get; set; }
    public string timezone_abbreviation { get; set; }
    public string elevation { get; set; }
    // 修正为单个对象,而非集合
    public Hourly_Units hourly_units { get; set; }
    public Hourly hourly { get; set; }
}

public class Hourly_Units
{
    public string time { get; set; }
    public string temperature_2m { get; set; }
}

public class Hourly
{
    public List<string> time { get; set; }
    public List<double> temperature_2m { get; set; }
}

2. 修正视图代码

因为hourly_units和hourly不再是集合,去掉foreach循环,直接访问属性并遍历内部集合:

@model WeatherModel

<form asp-controller="Home" asp-action="Index">
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<p>latitude: @Model.latitude</p>
<p>longitude: @Model.longitude</p>
<p>generationtime_ms: @Model.generationtime_ms</p>
<p>utc_offset_seconds: @Model.utc_offset_seconds</p>
<p>timezone: @Model.timezone</p>
<p>timezone_abbreviation: @Model.timezone_abbreviation</p>
<p>elevation: @Model.elevation</p>

<!-- 直接展示hourly_units的单位信息 -->
<p>单位信息: 
    时间格式: @Model.hourly_units.time | 
    温度单位: @Model.hourly_units.temperature_2m
</p>

<!-- 遍历逐小时的时间和温度数据 -->
<p>逐小时天气数据:</p>
@for(int i = 0; i < Model.hourly.time.Count; i++)
{
    <p>@Model.hourly.time[i] : @Model.hourly.temperature_2m[i] @Model.hourly_units.temperature_2m</p>
}

3. 验证效果

控制器代码无需修改,重新运行项目后,反序列化将正常完成,视图可正确展示所有天气数据,包括逐小时的时间和温度信息。

内容的提问来源于stack exchange,提问作者dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:25:57