JSONItem to Dictionary

I have JSON data that I am trying to load into a dictionary but I am having a Nil exception error.

I created a Property for the application called locations_dict as Xojo.Core.Dictionary.

The JSON data has an array within it called “exam_rooms” which I am trying to load into this dictionary. The array “exam_rooms” has two elements I want called “index” and “name”.

Everything seems to go smoothly until I try to add the items to a dictionary.

[code] Dim js As New JSONItem(s)
Dim results As JSONItem = js.Value(“results”)

If results.IsArray Then
  For i As Integer=0 To results.Count-1
    Dim item As JSONItem = results(i)
    Dim exam_rooms as JSONItem = item.Value("exam_rooms")
    If exam_rooms.IsArray Then
      For j As Integer=0 To exam_rooms.Count-1
        Dim item1 as JSONItem = exam_rooms(j)
        locations_dict.Value(item1.Value("index")) = item1.Value("name") //ERROR OCCURS HERE
      Next
    End If
    Exit
  Next
End If[/code]

The debugger shows locations_dict as Nil.

I tried entering the line:

Dim locations_dict as Xojo.Core.Dictionary

but that didn’t help.

I also tried Xojo.Data.ParseJSON but couldn’t get it to work.

You must have locations_dict declared somewhere, but your code doesn’t show it. (If you didn’t, your app wouldn’t run at all.) It sounds like you forgot to assign a new Dictionary to it.

That was it. I thought that since it was set up as a Property for the application that it was declared at that stage. I didn’t realize you had to declare it as a New Xojo.Core.Dictionary.

Do you have to cycle through the array to load it into the dictionary? I thought that JSON data could be loaded in one command with Xojo.Data.ParseJSON.

It can and will. The JSON string must be convertible to Text, and it’s up to you to know whether it represents an object or array at the top level. Code like this should do it:

dim json as auto = Xojo.Date.ParseJSON( myJSONString.ToText )

dim topDict as Xojo.Core.Dictionary
dim topArr() as auto

if Xojo.Introspection.GetType( json )= GetType( Xojo.Core.Dictionary ) then
  topDict = json
else
  topArr = json
end if

Note that on Windows and Linux, if the JSON string is sufficiently large, JSONItem will be faster and my JSONItem_MTC will be faster still. On Mac, the described process is usually faster.