ASP.NET Core Web API反序列化错误:无法转换JSON数组至PostViewModel
JSON数组反序列化错误的问题分析与解决
错误原因
错误信息明确显示:无法将JSON数组反序列化为PostViewModel类型。查看API返回的结构,data字段是Post对象数组,但你的泛型模型CustomActionResult<PostViewModel>中,Data属性的类型是单个PostViewModel对象,与返回的数组类型不匹配,导致反序列化失败。
解决方案
1. 修正泛型模型的类型参数
将泛型参数从PostViewModel改为List<PostViewModel>,让Data属性的类型对应JSON中的数组结构:
public IActionResult Index() { try { CustomActionResult<List<PostViewModel>> posts = new CustomActionResult<List<PostViewModel>>(); HttpResponseMessage response = _client.GetAsync(_client.BaseAddress + "/Blog/GetBlogs").Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; posts = JsonConvert.DeserializeObject<CustomActionResult<List<PostViewModel>>>(data); return View(posts); } } catch { throw new NotImplementedException(); } return View(); }
2. 确保属性名称与JSON字段匹配(可选)
JSON中的字段是小写的data、isSuccess、message,而模型属性是大写开头的Data、IsSuccess、Message。如果自动驼峰映射失效,可添加JsonProperty特性强制映射:
public class CustomActionResult { [JsonProperty("isSuccess")] public bool IsSuccess { get; set; } [JsonProperty("message")] public string Message { get; set; } } public class CustomActionResult<T> : CustomActionResult { [JsonProperty("data")] public T Data { get; set; } }
3. 优化HttpClient调用(可选)
避免使用.Result阻塞线程,改用异步模式提升性能和稳定性:
[HttpGet] public async Task<IActionResult> Index() { try { HttpResponseMessage response = await _client.GetAsync("/Blog/GetBlogs"); if (response.IsSuccessStatusCode) { string data = await response.Content.ReadAsStringAsync(); var posts = JsonConvert.DeserializeObject<CustomActionResult<List<PostViewModel>>>(data); return View(posts); } } catch { // 建议替换为具体的异常处理逻辑 throw new Exception("获取博客列表失败"); } return View(); }
验证
修改完成后,JSON中的data数组会被正确反序列化为List<PostViewModel>类型的Data属性,原错误即可解决。
内容的提问来源于stack exchange,提问作者Zephuris
相关产品推荐
相关产品推荐

