Would like to avoid invalidJSON error

I am catching an invalidJSON Exception but would like to know if there is a way to avoid this exception to begin with. If I request an invalid channel sent to a smart device from a URL Connection call, this error will occur.

Try
  Var json As Dictionary = ParseJSON(Content) //Error if incorrect channel selected
  If json.HasKey( "ison" ) Then
    Var status As Variant = json.Value( "ison" )
    
    ResultArea.Text = "" // Clear result area text
    ResultArea.AddText(status) // True or False
    
    Rem Manage radio buttons
    If status And S_OnButton.value = False Then 
      S_OnButton.value = True
    Elseif Not status And S_OffButton.value = False Then
      S_OffButton.value = True
    End
    
    Smart_Devices_Utility_Window.ShellyResultArea.Text = ""
    Smart_Devices_Utility_Window.ShellyResultArea.AddText(json.Value( "ison" ))+"  "+ URL // Result will happen for status check and radio push
    
  End
  
Catch json As InvalidJSONException
  MessageBox("Invalid channel selected.")
End Try
#Pragma BreakOnExceptions Default // Restore setting from Project menu

2020-12-20_13-10-05

Only way is to check the contents yourself before parsing to see if it’s really valid json. For example, if it doesn’t start with [ or {, it isn’t.

1 Like

And a stand-a-lone JSON editor can help you on such tasks. I’m using for instance http://www.smartjsoneditor.com/

In this case it appears in the debugger the “Content” was not found. Would that be a Nil or?

Check the URLConnection status code. If 200 then you should have json

You nailed it:

If DeviceType = "Sonoff" Then
  If HTTPStatus = 200 Then
    SD_Sonoff(content,URL)
  Else
    Channel.value = "0"
    MessageBox("Invalid channel selected.")
  End
Else
  If HTTPStatus = 200 Then
    SD_Shelly(content,URL)
  Else
    Channel.value = "0"
    MessageBox("Invalid channel selected.")
  End
End
2 Likes