A lot of APIs will give you responses in JSON format. Here we'll review JSON parsing in C# so that you can get to the interesting data faster.
This tutorial assumes that you've already gone through our C# getting started tutorial and are familiar with how our C# SDK works. Although we use the output from our YouTube ListSearchResults Choreo in this tutorial, the same steps we outline here will work for parsing any JSON in C#.
3 You get a whole bunch of JSON in the Response output. These are the results of the search. Next we'll see how to parse through this response in C# and pick out only the pieces we're interested in.
By default, C# encourages you to create concrete classes to use when parsing JSON data, as described in this article. However, when you want to experiment with data from multiple APIs, a more lightweight alternative is to use a generic third-party parsing library. In this tutorial we'll walk through installing a popular C# JSON parser and using it to work with the Youtube data.
4 Create a new Visual Studio solution containing a "C# Console Application" project.
6 Download the JSON.Net library and unzip the file. Move Newtonsoft.Json.dll into the directory where you keep your Visual Studio projects.
7 Under your "C# Console Application" project, right-click References and select Add Reference. In the dialogue box that appears, select Browse and select Newtonsoft.Json.dll. Click OK.
8 Replace the contents of Program.cs with the code below. In steps 9-11, we'll go over what happens in the code.
9First we converted the JSON text from the response to a C# Object using the JObject.Parse method.
For these results, we wanted the title of the first video in the search results. We got the items array, then the first item in that array (at index 0). Then we wanted the snippet object within the first item in the array. We used the statement json["items"]["snippet"] to grab this specific element within the JSON data.
11 To finish up, we parsed the title property from the snippet object using the firstItemSnippet["title"] accessor.
12All finished! Run the code in Visual Studio to try it out. You should see the title of your first YouTube Search result in the console.