c# - 从 Web API 恢复数据 [已解决]
问题描述
我有一个用 asp.net core 开发的 API,它允许对 DocumentType(文档的类型)进行 CRUD,旁边我有 asp.net core mvc Web 应用程序,我想从中恢复 DocumentType 列表,用于之间的通信我使用 HttpClient 的两个应用程序。以下是允许您检索文档列表的操作代码:
public async Task<IActionResult> Index()
{
List<DocumentType> documentTypeliste = new List<DocumentType>();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://localhost:44318/api/DocumentType"))
{
var apiResponse = await response.Content.ReadAsStringAsync();
documentTypeliste = JsonConvert.DeserializeObject<List<DocumentType>>(apiResponse);
}
}
return View(documentTypeliste);
}
但是我遇到了以下我仍然无法解决的错误。谢谢您的帮助
JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[GEDRH.Models.Entities.DocumentType]”,因为该类型需要 JSON 数组(例如 [1,2,3]) 以正确反序列化。要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。路径“成功”,第 1 行,位置 11。
解决方案
我解决了一个问题
public async Task<IActionResult> Index()
{
var documentTypeliste = new List<DocumentType>();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://localhost:44318/api/DocumentType"))
{
var apiResponse = await response.Content.ReadAsStringAsync();
var list = JObject.Parse(apiResponse)["data"].Select(el => new { Id = (int)el["id"], Name = (string)el["name"], Description = (string)el["description"] }).ToList();
//var names = list.Select(p => p.Name).ToList();
//var descriptions = list.Select(p => p.Description).ToList();
//var ids = list.Select(p => p.Id).ToList();
foreach(var it in list)
{
DocumentType dt = new DocumentType
{
Id = it.Id,
Name = it.Name,
Description = it.Description
};
documentTypeliste.Add(dt);
}
}
}
ViewBag.PersonTypeListe = _servicePersonType.SelectAll();
return View(documentTypeliste);
}
推荐阅读
- node.js - websocket自动关闭连接(node.Js)
- javascript - onClick : 从 componentDidMount 调用一个函数
- python - pandas 在添加新列时返回系列而不是数据框
- cloudera - 在 Cloudera Manager 中添加新的服务类型
- vue.js - Vue3:如何将对象从提供传递到索引
- selenium - 安装时黄瓜安装错误
- excel - VBA Dictionary - 通过键获取记录并写入工作表
- c - 忽略while循环中的scanf值
- javascript - 反应功能的计时器未正确启动
- roles - Spatie 权限管理在获取具有特定角色的用户时抛出错误