C# ASP DotNet Core MVC读取API JsonSerializer从另一个节点开始

C# ASP DotNet Core MVC读取API JsonSerializer从另一个节点开始,c#,api,asp.net-core,jsonserializer,C#,Api,Asp.net Core,Jsonserializer,反序列化json api时遇到问题。 这是我的api端点: 我遇到的问题是:无法将JSON值转换为行号为0 | BytePositionLine:1的System.Collections.Generic.IEnumerable 在以下位置失败:Books=wait JsonSerializer.DeserializeAsync(responseStream) 我认为原因是它从根开始解析,在那里它接收一个对象。 有没有办法跳过“种类”和“总体项目”节点,直接从“项目”节点开始 我找到了一种使用Js

反序列化json api时遇到问题。 这是我的api端点:

我遇到的问题是:无法将JSON值转换为行号为0 | BytePositionLine:1的System.Collections.Generic.IEnumerable

在以下位置失败:
Books=wait JsonSerializer.DeserializeAsync(responseStream)

我认为原因是它从根开始解析,在那里它接收一个对象。 有没有办法跳过“种类”和“总体项目”节点,直接从“项目”节点开始


我找到了一种使用
JsonDocument
实现这一点的方法。这不是很优雅,因为您基本上要对json进行两次解析,但它应该可以工作

var responseStream=wait response.Content.ReadAsStreamAsync();
//将查询结果解析为JsonDocument
var document=JsonDocument.Parse(responseStream);
//访问JsonDocument中的“items”集合
var booksElement=document.RootElement.GetProperty(“items”);
//获取集合的原始Json文本并将其解析为IEnumerable
//JsonSerializerOptions确保忽略区分大小写
Books=JsonSerializer.Deserialize(booksElement.GetRawText(),新的JsonSerializerOptions{propertynamecasensitive=true});

我使用了这个问题的答案来创建这个解决方案。

您的图书模型仍然不适合json中项目的结构。您可以使用一些在线json转换工具。
public async Task<IActionResult> Index()
    {
        var message = new HttpRequestMessage();
        message.Method = HttpMethod.Get;
        message.RequestUri = new Uri(URL);
        message.Headers.Add("Accept", "application/json");

        var client = _clientFactory.CreateClient();

        var response = await client.SendAsync(message);

        if (response.IsSuccessStatusCode)
        {
            using var responseStream = await response.Content.ReadAsStreamAsync();
            Books = await JsonSerializer.DeserializeAsync<IEnumerable<Book>>(responseStream);
        }
        else
        {
            GetBooksError = true;
            Books = Array.Empty<Book>();
        }

        return View(Books);
    }
public class Book
{
    [Display(Name = "ID")]
    public string id { get; set; }
    [Display(Name = "Title")]
    public string title { get; set; }
    [Display(Name = "Authors")]
    public string[] authors { get; set; }
    [Display(Name = "Publisher")]
    public string publisher { get; set; }
    [Display(Name = "Published Date")]
    public string publishedDate { get; set; }
    [Display(Name = "Description")]
    public string description { get; set; }
    [Display(Name = "ISBN 10")]
    public string ISBN_10 { get; set; }
    [Display(Name = "Image")]
    public string smallThumbnail { get; set; }
}