Android Code Snippet Check if a string is valid Json (isJson)

Hi
Like isBase64 posted here
https://www.b4x.com/android/forum/threads/check-if-a-string-is-base64-isbase64.98444/

here is the isJson function based on JSON documentation
B4X:
Sub is_Json(json As String) As Boolean
    If Regex.IsMatch($"[{\[]{1}([,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}"$, json.Trim) And json.Length > 2  Then
        Return True
    Else
        Return False
    End If
End Sub


example of use
B4X:
    Log(is_Json($"{"success":false,"msg":"teste!"}"$))
    Log(is_Json($"{"success":false,"msg":"$))

The result log is
true
false


Credits: stackoverflow, Douglas Farias and JSON documentation
 
Last edited:

Douglas Farias

Expert
Licensed User
Longtime User
2 options here.

B4X:
Dim j As HttpJob
j.Initialize("", Me)
j.Download("https://www.google.com")
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
  if is_Json(j.GetString) then
        'PARSE HERE
  End If
End If
j.Release

OR

B4X:
Dim j As HttpJob
j.Initialize("", Me)
j.Download("https://www.google.com")
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
    Try
        Dim jp As JSONParser
        jp.Initialize(j.GetString)
    Catch
        Log(LastException)
    End Try
End If
j.Release


I particularly prefer the if, but here is the 2 options, more options the better.
 

woniol

Active Member
Licensed User
Longtime User
2 options here.

B4X:
Dim j As HttpJob
j.Initialize("", Me)
j.Download("https://www.google.com")
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
  if is_Json(j.GetString) then
        'PARSE HERE
  End If
End If
j.Release

OR

B4X:
Dim j As HttpJob
j.Initialize("", Me)
j.Download("https://www.google.com")
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
    Try
        Dim jp As JSONParser
        jp.Initialize(j.GetString)
    Catch
        Log(LastException)
    End Try
End If
j.Release


I particularly prefer the if, but here is the 2 options, more options the better.

Hi,
B4X:
Try
        Dim jp As JSONParser
        jp.Initialize(j.GetString)
    Catch
        Log(LastException)
    End Try
is not enough. It will not raise an error even in string is not valid json.
no need to call JSONParser method:
B4X:
Dim jp As JSONParser
jp.Initialize(j.GetString)
jp.NextObject
for the error to be catched
 
Top