B4R Code Snippet JSON Parsing

Erel

Administrator
Staff member
Licensed User
Two methods to help parse JSON strings:
B4X:
Sub Process_Globals
   Public Serial1 As Serial
   Private jsontext() As Byte = "{  ""id"": ""84F3EBE3621A"",  ""name"": ""Kitchen"",  ""get_status"": ""0,1,1,1,0,1,1,0"",  ""set_status"": ""0,1,1,1,0,1,1,0"",  ""get"": {    ""index"": 8,    ""value"": 1  },  ""set"": {    ""index"": 8,    ""value"": 2  }}"
   Private quotearray() As Byte = """"
   Private LastIndex As Int
End Sub

Private Sub AppStart
   Serial1.Initialize(115200)
   Delay(100)
   Dim MaxSize As Int = 20
   Dim buffer(MaxSize) As Byte
   GetTextValueFromKey(jsontext, "name", 0, buffer, MaxSize)
   Log(buffer)
   GetTextValueFromKey(jsontext, "get_status", 0, buffer, MaxSize)
   Log(buffer)
   Log(GetNumberValueFromKey(jsontext, "value", 0))
   Log(GetNumberValueFromKey(jsontext, "value", LastIndex)) 'second value
End Sub

Sub GetTextValueFromKey (json() As Byte, Key() As Byte, StartIndex As Int, ResultBuffer() As Byte, MaxLength As UInt)
   Dim bc As ByteConverter
   Dim qkey() As Byte = JoinBytes(Array(quotearray, Key, quotearray))
   Dim i As Int = bc.IndexOf2(json, qkey, StartIndex)
   If i = -1 Then
       bc.ArrayCopy(Array As Byte(), ResultBuffer)
       Return
   End If
   Dim i1 As Int = bc.IndexOf2(json, quotearray, i + qkey.Length + 1)
   Dim i2 As Int = bc.IndexOf2(json, quotearray, i1 + 1)
   bc.ArrayCopy(bc.SubString2(json, i1 + 1, Min(i2, i1 + 1 + MaxLength)), ResultBuffer)
   LastIndex = i2
End Sub

Sub GetNumberValueFromKey (json() As Byte, Key() As Byte, StartIndex As Int) As Double
   Dim bc As ByteConverter
   Dim qkey() As Byte = JoinBytes(Array(quotearray, Key, quotearray))
   Dim i As Int = bc.IndexOf2(json, qkey, StartIndex)
   If i = -1 Then Return 0
   Dim colon As Int = bc.IndexOf2(json, ":", i + qkey.Length)
   Dim i2 As Int = 0
   For Each c As String In Array As String(",", "}", "]")
       i2 = bc.IndexOf2(json, c, colon + 1)
       If i2 <> -1 Then
           Exit       
       End If
   Next
   Dim res() As Byte = bc.SubString2(json, colon + 1, i2)
   LastIndex = i2 + 1
   res = bc.Trim(res)
   Dim s As String = bc.StringFromBytes(res)
   Dim value As Double = s
   Return value
End Sub
Depends on rRandomAccessFile.
 
Top