[VB.NET] Using JSON

Heres your chance to share your own tutorials with the community. Just post them on here. If your lucky they may even be posted on the main site.
1 post Page 1 of 1
Contributors
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

[VB.NET] Using JSON
comathi
JSON is a data transmitting format often used as an alternative to XML. It can be used with almost any programming language and is used by many APIs to return data.

In this tutorial I'm going to show you how to use JSON with VB.NET. This could be useful if you're planning on using the Codenstuff API, APIs in general, or just want an easy way to store and transfer data. For instance, I used JSON to store image data, ratings and descriptions in my Picture Base Mad March entry.

For the sake of this tutorial, let's create a new Windows Forms Application. Once that is done, you'll want to add the System.Web.Extension reference to your project:

Image
Image

Once that is done, we can add our imports statements at the top of our code:
Code: Select all
Imports System.Net
Imports System.Web.Script.Serialization
Next up, we're going to declare a Class that corresponds to the Object our JSON data will represent. For this tutorial, we're going to represent a list of people. Each person will have a first name, a last name, an age and a gender.

Let's create our Class Person and give it a few variables:
Code: Select all
Public Class Person
    Public FirstName As String
    Public LastName As String
    Public Age As String
    Public Gender As String
End Class
That's all for our custom class. We can now move on to our Form designer.

Add the following Controls to your form:

- A ListView named "peopleList"
- 4 TextBoxes named "fnameTXT", "lnameTXT", "ageTXT" and "genderTXT"
- 4 Labels for the TextBoxes
- A Button named "AddBTN"
- A Button named "RemoveBTN"

Add 4 columns to the ListView
Image

And make sure your ListView's "View" property is set to "Details".

Your Form should now look something like this:
Image


We can now move into our main Class (Form1).

The first thing we'll do is create a list of people. This will be where our JSON data is deserialized (parsed) and from our list we'll create JSON data.
Code: Select all
Public Class Form1
    Private people As New List(Of Person)
End Class
The next thing we'll do is load the file containing our JSON data when the form loads. Add the following code in Form1's Load event:
Code: Select all
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        If My.Computer.FileSystem.FileExists(Application.StartupPath & "\data.json") Then
            people = New JavaScriptSerializer().Deserialize(My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\data.json"), GetType(List(Of Person)))

            For Each p As Person In people
                Dim li As New ListViewItem(p.firstname)
                li.SubItems.Add(p.lastname)
                li.SubItems.Add(p.age)
                li.SubItems.Add(p.gender)

                peopleList.Items.Add(li)
            Next
        End If
 End Sub
The important part of this code, the part that will be new to you, is this:
Code: Select all
 people = New JavaScriptSerializer().Deserialize(My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\data.json"), GetType(List(Of Person)))
This line of code populates our list we created earlier. It deserializes the JSON data (parses it) and for each object in our JSON data, creates a new Person object. It knows which variables to populate because our JSON variables have the same name as our Person's variables.

The next part of code we'll want to put in is for our Form's Form_Closing event:
Code: Select all
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Dim serial As String = New JavaScriptSerializer().Serialize(people)
        My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\data.json", serial, False)
End Sub
This code does two things. First of all, it serializes our JSON data. It converts our people List into a JSON String. It then write that String to a file.

We'll now add a few basic features to add or remove data from our list:

Add a person
Code: Select all
Private Sub AddBTN_Click(sender As Object, e As EventArgs) Handles AddBTN.Click
        Dim p As New Person
        p.firstname = fnameTXT.Text
        p.lastname = lnameTXT.Text
        p.age = ageTXT.Text
        p.gender = genderTXT.Text

        Dim li As New ListViewItem(p.firstname)
        li.SubItems.Add(p.lastname)
        li.SubItems.Add(p.age)
        li.SubItems.Add(p.gender)

        people.Add(p)
        peopleList.Items.Add(li)
End Sub
Remove a person
Code: Select all
Private Sub RemoveBTN_Click(sender As Object, e As EventArgs) Handles RemoveBTN.Click
        Dim li As ListViewItem

        If peopleList.SelectedItems.Count > 0 Then
            li = peopleList.SelectedItems(0)

            people.RemoveAt(li.Index)
            peopleList.Items.RemoveAt(li.Index)
        End If
End Sub
You can now run your application, add people to the list, then close the application. You should then notice a file has been created in your application's debug folder. Open it with Notepad, it might look something like this:
Code: Select all
[{"firstname":"Cody","lastname":"Codenstein","age":"31","gender":"Male"},{"firstname":"Comathi","lastname":"Codes","age":"16","gender":"Male"},{"firstname":"Filip","lastname":"Sir","age":"16","gender":"Female"}]
That's the JSON data that was created from our Person Objects.

Now launch the program again. If everything works properly, the JSON data should be loaded into the application and your ListView populated
Image

That's it for this tutorial. You can now use JSON in your VB.NET applications. In short, this is what you need:

- A Class to represent the data in your JSON String (with appropriate variables).
- A List of Objects of the same type as the Class you just created
- The Serialize and Deserialize functions to parse and create JSON data

I hope you guys enjoyed the tutorial and will start using JSON in your apps a littel more cool;
1 post Page 1 of 1
Return to “Tutorials”