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

.NET 6 Blazor Server API调用:嵌套JSON反序列化及空引用问题

解决方案与优化建议

1. 解决JSON反序列化错误(StartArray转字符串失败)

你遇到的Cannot get the value of a token type 'StartArray' as a string错误,本质是JSON里的results是数组类型,但你对应的C#属性定义成了string,反序列化时类型不匹配导致的。

正确的做法是定义匹配JSON结构的嵌套实体类:

// 根响应类,匹配API返回的顶层结构
public class ApiResponse
{
    public int page { get; set; }
    public int total_pages { get; set; }
    public int total_results { get; set; }
    // 用List<T>接收JSON数组,T是results里单个对象的实体类
    public List<ResultItem> results { get; set; }
}

// 单个结果项的实体类,根据API返回的results里的字段定义
public class ResultItem
{
    public int id { get; set; }
    public string title { get; set; }
    public string overview { get; set; }
    // 其他你需要的字段,比如release_date、poster_path等
}

反序列化时直接用这个根类:

var response = await JsonSerializer.DeserializeAsync<ApiResponse>(await httpClient.GetStreamAsync("你的API地址"));

2. 解决NullReferenceException遍历错误

出现空引用异常,是因为results属性在反序列化后可能为null(比如API返回空数组或字段缺失),遍历前没做null检查。

两种解决方式:

  • 方式一:初始化默认值
    在实体类里给results设置默认空列表,避免null:
public List<ResultItem> results { get; set; } = new List<ResultItem>();
  • 方式二:Blazor组件里判空后遍历
    在Razor代码里先检查是否为null,再遍历:
@if (ApiResponse?.results != null)
{
    foreach (var item in ApiResponse.results)
    {
        <div>@item.title</div>
    }
}
else
{
    <p>暂无数据</p>
}

3. API调用优化建议

  • 直接用HttpClient的强类型反序列化:不用手动处理字符串,用GetFromJsonAsync<T>更简洁:
    var apiResponse = await httpClient.GetFromJsonAsync<ApiResponse>("你的API地址");
    
  • 添加异常处理:捕获网络错误、API返回非成功状态码的情况:
    try
    {
        var response = await httpClient.GetAsync("你的API地址");
        response.EnsureSuccessStatusCode(); // 抛出非200状态码的异常
        var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse>();
    }
    catch (HttpRequestException ex)
    {
        // 处理网络错误或API返回错误,比如显示错误提示
        ErrorMessage = $"请求失败:{ex.Message}";
    }
    
  • 启用Nullable引用类型:在项目文件里开启<Nullable>enable</Nullable>,编译时就能提前发现可能的null问题,避免运行时异常。
  • 分页加载优化:如果API支持分页,不要一次性请求所有数据,根据用户滚动或分页按钮加载对应页的数据,减少带宽占用和内存压力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:05:51