iOS Question How do I convert a JSON string to a Map object?

Mashiane

Expert
Licensed User
Hi

I have this json string

{'path':'and god said let there be light.jpg','text':'And God Said, Let There Be Light'}

How can I convert this to a map object?

I have tried this, but get an error when I try to return the size of the map or read a key?

B4X:
Sub JsonToMap(strJSON As String) As Map

    ' convert a json string to a map
    Dim jMap As Map
    jMap.Initialize
    Dim JSON As JSONParser
    JSON.Initialize(strJSON)
    jMap = JSON.NextObject
    Return jMap
End Sub
 

omidaghakhani1368

Well-Known Member
Licensed User
Hi.
the subrotine JsonToMap is write but your json string wrong.
test [{'path':'and god said let there be light.jpg','text':'And God Said, Let There Be Light'}]
 

Mashiane

Expert
Licensed User
Hi, thanks, I had tried that before and it did'nt work. I have just found the problem, it's the single quote. After replacing the single quote with double quote it's working perfectly with and without the square brackets. Thanks anyway, I corrected my routine below to use QUOTE instead of "'"

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
 
Top