首页 > 解决方案 > 从 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。

标签: c#jsonasp.net-core-mvcdotnet-httpclient

解决方案


我解决了一个问题

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);
    }

推荐阅读