Skip to content

Xojo Framework: Working with JSON

Much of the new Xojo framework is available for all project types staring with Xojo 2015r2. The Data namespace includes two methods for dealing with JSON data: GenerateJSON and ParseJSON. This is how they are used in comparison to JSONItem in the old “Classic” framework.

In the Classic framework the JSONItem class is used to create, load and output JSON data. With the new “Xojo” framework, you simply use a Dictionary, which you can easily populate from JSON data or output to JSON data.

For example, here is some JSON data to use as an example:

{ "Seagulls":
  { "players":
    { "Bob":{ "position":"1B" },
      "Tom":{ "position":"2B" } }
},
  "Pigeons":
  { "players":
    { "Bill":{ "position":"1B" },
      "Tim":{ "position":"2B" } }
},
  "Crows":
  { "players":
    { "Ben":{ "position":"1B" },
      "Ty":{ "position":"2B" } } }
}

With the above JSON data pasted into a TextArea, you can load it with just a single line of code:

Dim league As Dictionary = Xojo.Data.ParseJSON(JSONArea.Text.ToText)

This is similar to the classic framework, which would look like this:

Dim league As New JSONItem(JSONArea.Text)

Looping through the JSON data is also similar. In the Xojo framework, you just iterate through the Dictionary with each JSON section as its own Dictionary:

Dim teamName, playerName As TextDim team, players, player As Dictionary

For Each t As DictionaryEntry In league
  teamName = t.Key
  team = t.Value
  OutputArea.AppendText(teamName)
  OutputArea.AppendText(EndOfLine)
  players = team.Value("players")
  For Each p As DictionaryEntry In players
    playerName = p.Key
    player = players.Value(playerName)
    OutputArea.AppendText(" " + playerName + " ")
    For Each a As DictionaryEntry In player
      OutputArea.AppendText(a.Value + " ")
    Next
    OutputArea.AppendText(EndOfLine)
  Next
Next

In the Classic framework, you iterate through the count of items in the JSONItem:

Dim teamName, playerName As StringDim team, players, player As JSONItem

For i As Integer = 0 To league.Count-1
  teamName = league.Name(i)
  team = league.Value(teamName)
  OutputArea.AppendText(teamName)
  OutputArea.AppendText(EndOfLine)
  players = team.Value("players")
  For p As Integer = 0 To players.Count-1
    playerName = players.Name(p)
    player = players.Value(playerName)
    OutputArea.AppendText(" " + playerName + " ")
    For a As Integer = 0 To player.Count-1
      OutputArea.AppendText(player.Value(player.Name(a)) + " ")
    Next
    OutputArea.AppendText(EndOfLine)
  Next
Next

An example project for the above code is here.

To create JSON from a Dictionary, you use the the GenerateJSON method:

Dim d As New Xojo.Core.Dictionary
d.Value("Name") = "Bilbo Baggins"
Dim json As Text = Xojo.Data.GenerateJSON(d)

Grab Xojo 2015r2 and start using GenerateJSON and ParseJSON the Xojo framework today!



Watch Video