Xojo.Data.ParseJSON issue

The below code always throws “An exception of class TypeMismatchException was not handled. The application must shut down.”

[code]// save the JSON data
Using Xojo.IO
Using Xojo.Core

Dim noteDict As Dictionary
noteDict = New Dictionary

noteDict.Value(“Xojo”) = “test”

Dim json As Text
json = Xojo.Data.GenerateJSON(noteDict)

Dim file As FolderItem
file = SpecialFolder.Documents.Child(“test.dat”)

Dim output As TextOutputStream = Xojo.IO.TextOutputStream.Create(file, TextEncoding.UTF8)
output.Write(json)
output.Close[/code]

Saving the JSON data works as expected.

The below code crashes.

[code]// load the JSON data

Using Xojo.IO
Using Xojo.Core

Dim file As FolderItem
file = SpecialFolder.Documents.Child(“test.dat”)
If file Is Nil Or Not file.Exists Then Return

Dim inp As TextInputStream = Xojo.IO.TextInputStream.Open(file, TextEncoding.UTF8)
If inp Is Nil Then Return

Dim inputText As Text = inp.ReadAll

Dim json() As Auto

json = Xojo.Data.ParseJSON(inputText). -> this crashes with the TypeMismatchException

For Each j As Dictionary In json

MsgBox j.Value(“Xojo”)

Next[/code]

This is literally the code found in the Xojo examples (which also gives the same error).

Any thoughts?

ParseJSON might return a Xojo.Core.Dictionary or an array of Auto depending on the JSON it was given, but this code assumes it will be an array of Auto. But it’s not, so you get that exception.

["this", "is", "an", "array"]
{"this":"is an object"}
[{"this":"is"}, {"an array": "of objects"}]

Edit: I just checked and the documentation is correct. Look at the sample JSON used in each example.

Building on what Kem said, always start with Auto when parsing. Then use introspection to determine what you got back and work from there.

Thanks Kem and Thom. I now understand why the error pops up.