Introduction
JSON is a strange creature that you learn to love over time; LINQ, if you do not understand it, is the same. Today, I’d like to make your JSON and LINQ headaches disappear by showing you how to read JSON data using LINQ in Visual Basic.
LINQ
Language-Integrated Query (LINQ) adds query capabilities to Visual Basic. LINQ uses a unified syntax irrespective of the type of data. Instead of sending a query to a database, or working with different query syntax for different types of data that are being searched, LINQ provides queries as part of the Visual Basic language.
Practical
Open Visual Studio and create a new Visual Basic Windows Forms project. Design your form to resemble Figure 1. Keep in mind, as always, my object names may be different than yours.
Figure 1: Design
Add the following Namespaces to make it part of your Class:
Imports System.IO Imports System.Net Imports Newtonsoft.Json Imports Newtonsoft.Json.Linq
You may notice the bottom two Imports. These include external libraries from Newtonsoft. You can download these libraries from the link provided. After you have downloaded the Newtonsoft libraries(s), you need to set a reference to the .dll files. You do this by clicking Project, Add reference, Browse, and locating your .dll file.
Create a Modular variable that will hold your JSON string and populate it:
Private strIcons As String = "[ { 'Name': 'Chester', 'Surname': 'Bennington', 'Age': '41', 'Gender': 'm' }, { 'Name': 'Kurt', 'Surname': 'Cobain', 'Age': '27', 'Gender': 'm' }, { 'Name': 'Kirk', 'Surname': 'Hammet', 'Age': '55', 'Gender': 'm' }, { 'Name': 'Bruce', 'Surname': 'Dickensen', 'Age': '59', 'Gender': 'm' }, { 'Name': 'Dave', 'Surname': 'Mustaine', 'Age': '56', 'Gender': 'm' }, { 'Name': 'Freddie', 'Surname': 'Mercury', 'Age': '45', 'Gender': 'm' }, { 'Name': 'Axl', 'Surname': 'Rose', 'Age': '55', 'Gender': 'm' }, { 'Name': 'Prince', 'Surname': '-', 'Age': '57', 'Gender': 'm' } ]"
Even for the untrained eye, it should be quite apparent that there are eight objects inside this string. Each of these objects contain sub-items for name, Surname, Age and Gender. Each of these sub-items has its own content. Do not judge my taste in music… 🙂
Here is more information about JSON.
The trick now is to read this content and separate it logically. This is where LINQ is extremely powerful. Add the following code:
Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click Try GetIcons(strIcons) Catch ex As WebException MessageBox.Show("Error: " & ex.ToString()) End Try End Sub Private Sub GetIcons(strJSON As String) Dim Icons = JsonConvert.DeserializeObject(Of List(Of _ clsIcons))(strJSON) For Each Legend In Icons ListBox1.Items.Add(Legend.Name) Next End Sub Public Class clsIcons Public Name As String Public Surname As String Public Age As String Public Gender As String End Class
The geticons sub-procedure deserializes a JSON string and stores each segment neatly in a class named strIcons. When you run your project and click the first button, your list will be displayed inside the leftmost listbox (see Figure 2).
Figure 2: Name segments from the supplied JSON string
Add the following code behind the second button:
Private Sub Button2_Click(sender As Object, e As EventArgs) _ Handles Button2.Click Dim Icons = JsonConvert.DeserializeObject(Of List(Of _ clsIcons))(strIcons) Dim lstIcons = From Legend In Icons Where _ Legend.Name.Contains("Kurt") Select Legend For Each Legend In lstIcons ListBox2.Items.Add("Icon: " & Legend.Name & " " _ & Legend.Surname & " Age: " + Legend.Age) Next End Sub
The preceding code manipulates the JSON object a bit further and enables you to loop through each of the items inside the JSON list with the help of LINQ. Figure 3 shows this code in action.
Figure 3: JSON read with the help of LINQ
Usually, a JSON string gets supplied in the form of a file. Let’s add that code now:
Dim srIcons As StreamReader Try Dim strURL As String = "http://website.com/ _ calltoJSONfunction?iconlist=legends&format=json" Dim wrIcons As HttpWebRequest = _ CType(WebRequest.Create(strURL), HttpWebRequest) Dim wrReponse As HttpWebResponse = _ CType(wrIcons.GetResponse(), HttpWebResponse) srIcons = New StreamReader(wrReponse.GetResponseStream()) Dim strInput As String = srIcons.ReadToEnd() GetIcons(strIcons) Catch ex As WebException MessageBox.Show("Error: " & ex.ToString()) End Try End Sub
Here, you make use of the System.Net functionalities to read the JSON file from the supplied URL. Figure 4 shows this code in action:
Figure 4: JSON read from a file
The code for this article is available on GitHub.
Conclusion
JSON is not too complicated to understand; neither is LINQ. This is just the tip of the iceberg, though. The onus is now on you to take what you have learned today further.