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

.NET MAUI中System.Text.Json反序列化ViewModel列表属性未填充问题

问题解决:System.Text.Json反序列化属性未填充的问题

问题根源

  • System.Text.Json默认区分大小写,API返回的JSON字段为小写开头(如date、temperatureC),但你的WeatherViewModel属性是大写开头(如Date、TemperatureC),导致字段无法匹配映射。
  • TemperatureF是计算属性,不需要从JSON反序列化,JSON中的对应字段会被System.Text.Json尝试解析,但因为是只读属性,也会影响反序列化逻辑。

解决方案1:修改序列化配置,开启大小写不敏感

在JsonSerializerOptions中添加大小写不匹配支持,同时忽略只读属性:

var response = client.GetAsync("WeatherForecast?format=json").Result;
if (response.IsSuccessStatusCode)
{
   var options = new JsonSerializerOptions 
   { 
       WriteIndented = true,
       // 开启大小写不匹配自动映射
       PropertyNameCaseInsensitive = true,
       // 忽略只读属性,避免解析TemperatureF
       IgnoreReadOnlyProperties = true
   };
   var responseData = JsonSerializer.Deserialize<List<WeatherViewModel>>(response.Content.ReadAsStringAsync().Result, options);
}

解决方案2:显式字段映射(精准控制)

在ViewModel属性上添加[JsonPropertyName]特性指定JSON字段名,同时标记计算属性为忽略:

using System.Text.Json.Serialization;

public class WeatherViewModel
{
    [JsonPropertyName("date")]
    public DateTime Date { get; set; }

    [JsonPropertyName("temperatureC")]
    public Int32 TemperatureC { get; set; }

    // 标记为不参与序列化/反序列化
    [JsonIgnore]
    public Int32 TemperatureF => 32 + (int)(TemperatureC / 0.5556);

    [JsonPropertyName("summary")]
    public String Summary { get; set; }
}

补充说明

Newtonsoft.Json默认启用了驼峰命名解析器,会自动处理大小写匹配,因此之前代码可以正常工作;而System.Text.Json默认严格区分大小写,需要手动配置或显式映射才能实现相同效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:15:57