尝试从api解析json时出现RuntimeBinderException

时间:2015-01-09 00:40:23

标签: c# json json.net

我最近开始学习如何从REST API获取数据,我遇到了一个问题。

到目前为止,这是我的代码:

   <!-- language-all: lang-c# -->

   using System...
   using Newtonsoft.Json.Linq; 
   //I use JSON.NET V.6.0.7 for faster and less complicated parsing
   ...
   ...

    WebClient client = new WebClient(); //Creates the client
    Stream stream = client.OpenRead("INSERT API URL HERE"); //Calls the API
    StreamReader reader = new StreamReader(stream); //Convert the information

    dynamic data = JObject.Parse(reader.ReadToEnd()); //Parses JSON into an object

    Console.WriteLine(data); //Writes out the information


        }
    }
}

到目前为止,我的代码工作正常,唯一的问题是我一次获得了大量不必要的信息

我尝试将Console.WriteLine(data);更改为Console.WriteLine(data.author);

试图获取所有作者的姓名,而我却收到错误

未处理的类型&#39; Microsoft.CSharp.RuntimeBinder.RuntimeBinderException&#39;发生在System.Core.dll

为什么?我该如何解决?

我尝试过寻找答案,但我确实找到了类似的帖子here,但这对我没有帮助。

非常感谢任何帮助!

我的母语不是英语,所以我为任何奇怪的语法使用/拼写错误道歉。

1 个答案:

答案 0 :(得分:0)

您的JSON(您未在问题中包含的内容)不得包含名为author的顶级对象。每当您尝试use a property of a dynamic object that does not exist时,都会抛出该异常。因此,author不能作为顶级JSON对象存在。检查以确保您具有正确的字段名称;也许它实际上是Author或类似的东西。或者它可能嵌套在一些你需要提取的中间容器中。

如果您确实拥有正确的字段名称,并且在某些情况下似乎没有显示,则可以使用try/catch块,或者解析为JToken而不是dynamic并使用用于访问数据的Linq to Json方法,例如:

var jToken = JToken.Parse(reader.ReadToEnd());

var author = jToken["author"];
if (author != null)
    Console.WriteLine(author.ToString());

如果您不确定JSON字符串的结构,因为它非常长并且没有缩进,您可以执行Debug.WriteLine(JToken.Parse(reader.ReadToEnd()),在这种情况下,Json.NET将为您输出缩进的格式化版本。 / p>

相关问题