c# - 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; }
}
解决方案
我找到了一种使用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 });
我使用这个问题的答案来创建这个解决方案。
推荐阅读
- android-studio - 在活动之间切换时的空引用
- c# - 从 Startup.cs 中的 appsettings.json 访问值
- css - 使用 css 和 vue 进行设置
- python-3.x - Python:使用 CP2102 模块通过 UART 与设备通信
- webstorm - 在 WebStorm 中显示上下文操作的快捷方式不起作用
- python - 如何从 XPATH 中使用 Selenium 检索变量(如计数)
- c++ - 从输入到输出的哈希表
- python - 调用外部函数时使用导入的正确方法
- python-3.x - 计算非 gensim 主题模型的连贯性
- django - 如何在 GitHub 操作中使用 django selenium 测试?