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

Blazor中Json反序列化返回空对象问题求助

问题解决方法

核心原因

问题出在JSON属性名称与C#类属性名称的大小写不匹配。你提供的JSON里字段都是小写开头(比如id、description),但GridList类的属性是大写开头(Id、Description),默认情况下System.Text.Json序列化器区分大小写,导致字段值无法正确映射,最终生成空对象。

两种解决方法

方法1:给类属性添加映射特性

修改GridList类,为每个属性加上[JsonPropertyName]特性,指定对应的JSON字段名:

@code {
    using System.Text.Json.Serialization;

    [JsonPropertyName("id")]
    public int Id { get; set; }
    [JsonPropertyName("description")]
    public string Description { get; set; }
    [JsonPropertyName("position")]
    public int Position { get; set; }
    [JsonPropertyName("enabled")]
    public bool Enabled { get; set; }
    [JsonPropertyName("itemSections")]
    public List<string> ItemSections { get; set; }
    [JsonPropertyName("users")]
    public List<string> Users { get; set; }
}

方法2:配置序列化器忽略大小写

在反序列化时传入配置选项,让序列化器忽略大小写差异:

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};
items = JsonSerializer.Deserialize<List<GridList>>(jsonDocument.RootElement, options);

额外优化:用Flurl直接反序列化

既然你在用Flurl,完全可以跳过手动解析JSON的步骤,用它内置的反序列化功能,代码更简洁:

var tokenTrimmed = token2.Split("\"token\":\"")[1].Split('"')[0].Trim();
items = await url.WithOAuthBearerToken(tokenTrimmed).GetJsonAsync<List<GridList>>();

如果需要大小写忽略,同样可以传配置:

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
items = await url.WithOAuthBearerToken(tokenTrimmed).GetJsonAsync<List<GridList>>(options);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:26:16