ASP.NET Core MVC三层架构下解析API返回JSON数组时遇字符解析错误的技术咨询
解决ASP.NET Core MVC中解析部门列表JSON的反序列化错误
嘿,这个错误我见得不少——问题出在JSON结构和你反序列化的类型不匹配上。你的API返回的是一个部门对象的数组(就是JSON里开头的[),但你大概率是把单个Department对象作为泛型参数传给了GetRequest<T>,所以Json.NET尝试把数组解析成单个对象,直接就懵了,抛出那个Unexpected character错误。
咱们一步步来修复:
1. 核心问题:泛型类型要对应数组结构
你的JSON是[{...}, {...}]这种数组格式,所以反序列化的时候必须用List<Department>(或者IEnumerable<Department>)作为泛型类型,而不是单个Department对象。
2. 修复GetRequest方法里的坑
你的方法里有几个小问题,先一并解决:
responseBody变量没有提前声明,会导致编译错误- 判断响应状态码的方式太生硬,用
IsSuccessStatusCode更靠谱 - 异常处理里还强行反序列化空的
responseBody,这只会雪上加霜
修正后的方法代码:
public async Task<T> GetRequest<T>(string uri) { string responseBody = string.Empty; // 提前初始化responseBody try { var client = _httpClientFactory.CreateClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); using (HttpResponseMessage response = await client.GetAsync(uri)) { if (response.IsSuccessStatusCode) { _logger.LogInformation("Get Request Succeeded"); responseBody = await response.Content.ReadAsStringAsync(); } else { _logger.LogWarning($"Get Request failed with status code: {response.StatusCode}"); return default(T); // 请求失败时返回默认值,避免后续反序列化出错 } return JsonConvert.DeserializeObject<T>(responseBody); } } catch (Exception ex) { _logger.LogError(ex, "Failed to execute Get Request"); // 记录完整异常信息,方便排查 return default(T); } }
3. 正确调用方法获取部门列表
首先确保你有和JSON字段匹配的Department实体类:
public class Department { public int Id { get; set; } public string Name { get; set; } }
然后在你的MVC控制器里这样调用:
// 假设你注入了包含GetRequest方法的服务 var departmentList = await _apiService.GetRequest<List<Department>>("https://your-api-url/api/departments"); // 把列表传给视图 return View(departmentList);
4. 在Razor视图里展示列表
最后在视图里接收List<Department>模型,循环展示即可:
@model List<Department> <h2>部门列表</h2> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>部门ID</th> <th>部门名称</th> </tr> </thead> <tbody> @foreach (var dept in Model) { <tr> <td>@dept.Id</td> <td>@dept.Name</td> </tr> } </tbody> </table> </div>
额外提示
如果你的JSON字段和C#属性名不匹配(比如JSON是department_id而C#是Id),可以用[JsonProperty]特性显式映射:
public class Department { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } }
不过你现在的JSON字段和C#属性是驼峰和帕斯卡的对应,Json.NET默认会自动匹配,所以这一步可以跳过。
内容的提问来源于stack exchange,提问作者Basma
相关产品推荐
相关产品推荐

