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
Code: Copy
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
Code: Copy
    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:
2 options here.

Code: Copy
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

Code: Copy
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.
 
2 options here.

Code: Copy
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

Code: Copy
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,
Code: Copy
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:
Code: Copy
Dim jp As JSONParser
jp.Initialize(j.GetString)
jp.NextObject
for the error to be catched
 
Back
Top