Hi!
I have two possibilities receiving a JSON:
First: {“idStore”:“1”}
Second: {“idStore”:[“1”,“2”]}
[code]dim json as new JSONItem(jsonData)
dim stores as string
Try
stores = json.Value(“idStore”) // just one idStore
Catch e As TypeMismatchException
stores = json.Child(“idStore”).ToString // more than one idStore
End Try
[/code]
This was the only way i found to put both cases onto stores string.
Is there another way to do that? HOW???
Dim stores as a Variant instead, then check to see if it’s an array or a string.
Don’t work. It’s TypeMismatchException
Please post your new code.
Another example didn’t work with my problem
dim jsonDict as Xojo.Core.Dictionary
jsonDict = xojo.data.ParseJSON(jsonData)
dim idStores() as Auto
idStores = jsonDict.value("idStores")
dim concatena as string
for each id as text in idStores
MsgBox id
next
break
(extracted from xojo’s webinar)
With First: {“idStore”:“1”} it’s TypeMismatchException
on Second: {“idStore”:[“1”,“2”]} works
I need to be able to receive idStore with only one id AND idStore with more than one id
Your JSON described an object (Dictionary) with one key whose value might be a string or an array. Your first code expects a string so an array causes an exception. The second code does the opposite. It expects an array and get an exception when it’s a string instead.
Try something like this instead:
dim json as new JSONItem(jsonData)
dim storesValue as variant = json.Value( "idStore" )
if storesValue.Type = Variant.TypeString then
dim store as string = storesValue
// Do something with it
else // It's an array
dim stores as JSONItem = storesValue
for index as integer = 0 to stores.Count - 1
dim store as string = stores( index )
// Do something with it
next
end if
YES!!!
How did I not see it? It was so obvious!
Thank you very much!
[code]dim jsondata as string = " {‘idStore’:[‘1’]}"
jsondata = replaceall(jsondata,"’",chr(34))
dim json as new JSONItem(jsonData)
dim stores as jsonitem
dim var as variant
stores = json.Value(“idStore”)
if stores.IsArray then
for x as integer = 0 to stores.count -1
msgbox stores(x)
next
else
//is a dictionary
end if[/code]
edit: you beat me to it!