Hello,
Is there a way to check if a text is a json item?
I have a webservice that if everything is ok it respond me “Everything is ok” else the response is {“Message”:“Error”}
Thanks
Hello,
Is there a way to check if a text is a json item?
I have a webservice that if everything is ok it respond me “Everything is ok” else the response is {“Message”:“Error”}
Thanks
[code] dim json As JSONItem
try
json = new JSONItem(sourceText)
//parsed ok, use json
catch JSONException
//not json
end
//json nil here if didn’t parse
[/code]
or if you don’t need the json object outside of the ‘try’ it’s just
try
dim json As new JSONItem(sourceText)
//parsed ok, use json
catch JSONException
//not json
end
Here is Will’s method wrapped as an EXTENDS method for easy use:
Function IsJSON(extends t As Text) As Boolean
Dim json As JSONItem
try
json = new JSONItem(t)
Catch JSONException
end
return (json <> nil)
End Function
Simply copy this function to a module and make sure to set the scope to Global.
You can now check any text in your project like follow:
if myText.IsJSON() then
// do something
end if
All good except I’d use the new framework instead of JSONItem. It’s faster and more accurate.
Thanks for the tip Kem.
Is the new framework JSON class available in version 2015 R2.1 of Xojo? I’d like to refactor my app to use the new framework JSON classes but can’t seem to find any classes in xojo.Core or xojo.Data that is JSON related?
Yes, the JSON stuff from the new framework is available for all project types in 2015r2. There are no JSON classes, just two methods: Xojo.Data.ParseJSON and Xojo.Data.GenerateJSON.
Ah, got it. Thanks Paul.
Here is my version of that code:
Function IsValidJSON_MTC(Extends src As Text) As Boolean
#pragma BreakOnExceptions false
try
dim a as Auto = Xojo.Data.ParseJSON( src )
#pragma unused a
return true
catch err as Xojo.Data.InvalidJSONException
return false
end try
#pragma BreakOnExceptions default
End Function
This will be in my M_Text module.
It doesn’t appear to handle all valid JSON, though–an array of arrays would create something the docs don’t appear to support. Not to mention, finding the datatypes on the primitives would appear to be a royal pain if you don’t know in advance what they should be (likely to be the case if you aren’t even sure you have JSON in the first place).
An array of arrays is not an issue since each array is of type Auto. Use Introspection to determine the type of each element.