ASP DotNet Core MVC Reading API JsonSerializer 从另一个节点启动

ASP DotNet Core MVC Reading API JsonSerializer start from another node

我在反序列化 json api 时遇到问题。 这是我的 api 端点:https://www.googleapis.com/books/v1/volumes?q=harry+potter

我遇到的问题是:JSON 值无法在 LineNumber: 0 | 处转换为 System.Collections.Generic.IEnumerable BytePositionInLine:1

失败于:Books = await JsonSerializer.DeserializeAsync<IEnumerable<Book>>(responseStream);

我认为原因是它从接收对象的根开始解析。 有没有办法跳过“kind”和“totalItems”节点,直接从“items”节点开始?

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

型号Class:

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

我找到了使用 JsonDocument 执行此操作的方法。它不是很优雅,因为你基本上解析了 json 两次,但它应该可以工作。

var responseStream = await response.Content.ReadAsStreamAsync();

// Parse the result of the query to a JsonDocument
var document = JsonDocument.Parse(responseStream);

// Access the "items" collection in the JsonDocument
var booksElement = document.RootElement.GetProperty("items");

// Get the raw Json text of the collection and parse it to IEnumerable<Book> 
// The JsonSerializerOptions make sure to ignore case sensitivity
Books = JsonSerializer.Deserialize<IEnumerable<Book>>(booksElement.GetRawText(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

我使用这个 question 的答案来创建这个解决方案。