Android Code Snippet JSON - GetObjFromPath()

This code helps you navigate JSON trees like a boss!
Demo project attached. Snipped below.



B4X:
Sub GetObjFromPath(obj As Object, path As String) As Object
    Dim keys() = Regex.Split("/", path) As String : path = ""
    If keys.Length == 0 Then Return obj
    '--------------------------------------------------------
    Dim key As String
    For i = 0 To (keys.Length - 1)
        key = keys(i) : If key <> "" Then Exit
    Next
    If key.Length == 0 Then Return obj
    '--------------------------------------------------------
    For j = i + 1 To (keys.Length - 1)
        path = path & keys(j) & "/"
    Next
    If obj Is Map Then
        Dim map = obj As Map
        obj = GetObjFromPath(map.GetDefault(key, Null), path)
    Else If obj Is List Then
        Dim lst = obj As List
        Try
            obj = GetObjFromPath(lst.Get(key), path)
        Catch
            obj = Null
        End Try
    End If
    Return obj
End Sub

Usage:
B4X:
Dim jstr = $"{ "Key A": "value", "Key B": "[1, 2, 3, 4, 5]", "Key C": { "Key X" : "value", "Key Y": "value" } }"$
Dim jp As JSONParser : jp.Initialize(jstr)
Dim map = jp.NextObject As Map

Dim myInt As Int    = GetObjFromPath(map, "/Key B/2")
Dim myLst As List   = GetObjFromPath(map, "/Key B")
Dim myMap As Map    = GetObjFromPath(map, "/Key C")
Dim myStr As String = GetObjFromPath(map, "/Key C/Key Y")
 

Attachments

  • like a boss.zip
    1.5 KB · Views: 453
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…