首页 > 解决方案 > ASP DotNet Core MVC 读取 API JsonSerializer 从另一个节点开始

问题描述

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

我遇到的问题是: JSON 值无法在 LineNumber 处转换为 System.Collections.Generic.IEnumerable:0 | 字节位置行内: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);
    }

型号类:

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

标签: c#apiasp.net-corejsonserializer

解决方案


我找到了一种使用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 });

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


推荐阅读