1
votes

I have recently begun learning how to GET data from REST APIs, and I have encountered a problem.

This is my code so far:

   <!-- 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


        }
    }
}

So far my code works fine, and the only issue is that I get a lot of unnecessary information at once

I tried changing Console.WriteLine(data); to Console.WriteLine(data.author);

In an attempt to get all of the authors name, and instead I got an error saying

An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll

Why is that? And How can I Fix it?

I have tried searching for the answer and I did find a similar thread here, but it did not help me.

Any help will be much appreciated!

My native language is not in English, so I apologize any weird grammar use/misspelling.

1
What does the json look like? Does it have an object named "author"? - dbc

1 Answers

0
votes

Your JSON (which you did not include in your question) must not contain a top-level object named author. That exception is thrown whenever you try to use a property of a dynamic object that does not exist. Thus, author must not exist as a top level JSON object. Check to make sure you have the the correct field name; perhaps it's actually Author or something similar. Or possibly it is nested in some intermediate container which you will need to extract.

If you do have the correct field name, and it simply does not appear in some cases, you can use a try/catch block, or parse to JToken instead of dynamic and use Linq to Json methods for accessing data, e.g.:

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

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

If you are unsure of the structure of your JSON string, because it is very long and not indented, you can do Debug.WriteLine(JToken.Parse(reader.ReadToEnd()), in which case Json.NET will output an indented, formatted version for you.