MAUI Blazor中JSON反序列化后列表无法显示问题求助
问题排查与解决方案
1. 捕获反序列化异常,定位具体错误
当前代码未处理反序列化异常,导致报错时无法知晓问题根源。修改OnInitializedAsync方法,添加异常捕获逻辑并在页面展示错误信息:
@* 在页面顶部新增错误提示区域 *@ @if (!string.IsNullOrEmpty(errorMessage)) { <div class="alert alert-danger">@errorMessage</div> } @* 原页面内容保留 *@ @code { private string errorMessage; List<InQuestion> Questions = new List<InQuestion>(); protected override async Task OnInitializedAsync() { string jwturl = "https://quizapijwt.azurewebsites.net/api/"; using (var client1 = new HttpClient()) { client1.BaseAddress = new Uri(jwturl); client1.DefaultRequestHeaders.Clear(); client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client1.GetAsync("RateCards"); if (response.IsSuccessStatusCode) { jsonString = await response.Content.ReadAsStringAsync(); try { Questions = JsonConvert.DeserializeObject<List<InQuestion>>(jsonString); } catch (Exception ex) { errorMessage = $"反序列化失败: {ex.Message}\n{ex.InnerException?.Message}"; errorMessage += $"\n返回的JSON内容: {jsonString}"; } } else { errorMessage = $"请求失败,状态码: {response.StatusCode}"; } } } }
2. 消除类定义冲突
你同时引用了RateApp.Models命名空间,又在@code块内重复定义了InQuestion类,这会导致类型混淆。删除@code内的InQuestion定义,直接使用模型层的类:
@code { // 移除内部的InQuestion类定义 List<RateApp.Models.InQuestion> Questions = new List<RateApp.Models.InQuestion>(); // 其余代码保持不变 }
3. 确保JSON与类属性的映射匹配
检查WebAPI返回的JSON字段名和类属性名是否完全匹配(包括大小写)。若JSON字段为小写(如"no")而类属性为No,可通过JsonProperty特性显式映射:
// 在RateApp.Models.InQuestion类中添加特性 public class InQuestion { [JsonProperty("no")] public int No { get; set; } [JsonProperty("daysBegin")] public int DaysBegin { get; set; } [JsonProperty("daysEnd")] public int DaysEnd { get; set; } [JsonProperty("interest")] public decimal Interest { get; set; } [JsonProperty("srInterest")] public decimal SrInterest { get; set; } }
4. 使用MAUI推荐的注入式HttpClient
MAUI中不建议手动实例化HttpClient,改用依赖注入方式获取,避免连接复用问题:
@inject HttpClient HttpClient @code { protected override async Task OnInitializedAsync() { string jwturl = "https://quizapijwt.azurewebsites.net/api/RateCards"; try { var response = await HttpClient.GetAsync(jwturl); if (response.IsSuccessStatusCode) { jsonString = await response.Content.ReadAsStringAsync(); Questions = JsonConvert.DeserializeObject<List<RateApp.Models.InQuestion>>(jsonString); } else { errorMessage = $"请求失败: {response.StatusCode}"; } } catch (Exception ex) { errorMessage = $"请求或反序列化出错: {ex.Message}"; } } }
同时在MauiProgram.cs中注册HttpClient服务:
builder.Services.AddHttpClient();
5. 强制组件刷新(可选)
若反序列化成功但页面未更新,可在反序列化后调用StateHasChanged()触发组件刷新:
Questions = JsonConvert.DeserializeObject<List<RateApp.Models.InQuestion>>(jsonString); StateHasChanged();
内容的提问来源于stack exchange,提问作者KALYANA ALLAM
相关产品推荐
相关产品推荐

