iOS Code Snippet Map to JSON String

Mashiane

Expert
Licensed User
This converts your map object to a JSON string. I have updated this post to have the right b4i version to do this using jsonGenerator...

B4X:
Sub MapToJSON(sm As Map, bEnclose As Boolean) As String
    ' convert a map to a json string and specify if you want the
    ' returned string enclosed, the default behavour is true
    ' clean the map values and ensure there is no quoted values or keys
    Dim mout As Map
    mout.Initialize 
    For Each mKey As String In sm.Keys
        ' get value for each key
        Dim mValue As String = sm.Get(mKey)
        mValue = mValue.Replace(QUOTE, "")
        mKey = mKey.Replace(QUOTE,"")
        mout.Put(mKey, mValue)
    Next
    ' convert map to list
    Dim values As List = Array(mout)
    Dim jsonG As JSONGenerator
    ' pass list to json generator
    jsonG.Initialize2(values)
    Dim output As String = jsonG.ToString 
    If bEnclose = True Then
        Return output
    Else
        output = output.Replace("[{","")
        output = output.Replace("}]","")
        Return output
    End If
End Sub
You have an option to include brackets or not. Below was incorrect as indicated by Erel.

B4X:
Sub MapToJSON(sm As Map, bEnclose As Boolean) As String
    ' convert a map to a json string
    Dim iCnt As Int
    Dim iTot As Int
    Dim sb As StringBuilder
    sb.Initialize
    If bEnclose = True Then sb.Append("{")
    ' get size of map
    iTot = sm.Size - 1
    iCnt = 0
    For Each mKey As String In sm.Keys
        Dim mValue As String = sm.Get(mKey)
        sb.Append(QUOTE).Append(mKey).Append(QUOTE).Append(":").Append(QUOTE)
        sb.Append(mValue).Append(QUOTE)
        If iCnt < iTot Then sb.Append(",")
        iCnt = iCnt + 1
    Next
    If bEnclose = True Then sb.Append("}")
    Return sb.ToString
End Sub
 
Last edited:
Top