C# 导航 JSON 结构嵌套返回 NullReferenceException

C# Navigating JSON structure nest returning NullReferenceException

我正在使用 OpenLibrary API 从书籍的 ISBN 号收集信息 我创建了一个简单的 JSON 设置,但无法让它从嵌套结构中检索值。

link到JSON是:http://openlibrary.org/api/books?bibkeys=ISBN:0747532699&jscmd=details&format=json

我正在尝试访问“标题”值。在这种情况下,它应该 return: Harry Potter and the Philosopher's Stone

我的代码是:

Console.WriteLine("Enter the ISBN: ");
String isbn = Console.ReadLine();
String url = "http://openlibrary.org/api/books?bibkeys=ISBN:" + isbn + "&jscmd=details&format=json";
String json = new WebClient().DownloadString(url);

JObject jsonObject = JObject.Parse(json);
JToken details = jsonObject["ISBN:" + isbn + ".details"];
String title = (string) details["title"];
Console.WriteLine(title);

错误是 System.NullReferenceException(Object 引用未设置到 object 的实例),这是在行 JToken details = jsonObject["ISBN:" + isbn + ".details"];

上引起的

我在其他问题上看到使用 .字符通过结构,但我似乎无法使任何工作。

提前致谢。

您需要使用 SelectToken(),您的代码才能正常工作。

Console.WriteLine("Enter the ISBN: ");
String isbn = "0747532699";
String url = "http://openlibrary.org/api/books?bibkeys=ISBN:" + isbn + "&jscmd=details&format=json";
String json = new WebClient().DownloadString(url);

JObject jsonObject = JObject.Parse(json);
JToken details = jsonObject.SelectToken("ISBN:" + isbn + ".details");
String title = (string)details["title"];
Console.WriteLine(title);