string.toText error

Can anyone tell me why Encodings.SystemDefault to text works and Encodings.UTF8 fails?

Just wondering. I am using Xojo 2018r3 Desktop on a Mac.

“results” is a valid JSONItem which I have checked to be valid.

//no error
Dim jsonArray() As Auto
jsonArray = Xojo.Data.ParseJSON(results.ToString.DefineEncoding(Encodings.SystemDefault).ToText)

//Runtime error “The data cannot be converted to text with this encoding”
Dim jsonArray() As Auto
jsonArray = Xojo.Data.ParseJSON(results.ToString.DefineEncoding(Encodings.UTF8).ToText)

The bytes that end up in the string are not valid UTF-8.

But isn’t results Text to start with? If so, none of that is necessary.

Results is a JSONItem but generates an error in this line:

jsonArray = Xojo.Data.ParseJSON(results)

because text is expected - but there is no “results.ToText” function so I had to convert it to string and then to text.

I am retrieving a JSON response to a cURL request and placing it in a string:

//Get the result of sent message
Dim s As String = Mid(sh.Result,InStr(sh.Result,"{"))
Dim js As New JSONItem

Try
js.Load(s.DefineEncoding(Encodings.UTF8))
Catch e as JSONException
MsgBox “Sorry. Error found when loading records.”
Return
End Try

Dim results As JSONItem = js.Value(“content”)

Dim jsonArray() As Auto
jsonArray = Xojo.Data.ParseJSON(results.ToString.DefineEncoding(Encodings.SystemDefault).ToText)

So if I load the result into a text variable (mytext), would this make the content of the JSONItem (js) then contain text instead of a string in the line js.Load(mytext)?

Once you have a JSONItem, you don’t have to do any further processing on it. If it represents a JSON array, just use it like an array:

dim v as Variant = results( 0 )

If you prefer to work directly with arrays and Dictionaries, and have a recent version of Xojo, you can skip JSONItem like this:

var s as string = theJsonString
var dict as Dictionary = ParseJSON( s )
var result() as variant = dict.Value( "content" )

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.