微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决ASP DotNet Core MVC读取API JsonSerializer从另一个节点开始

我在反序列化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);

我认为原因是它正在从接收对象的根开始进行解析。 是否可以跳过“种类”和“ totalItems”节点并直接从“项目”节点开始?

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

解决方法

我找到了一种使用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的答案来创建此解决方案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。