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

Discussion in 'iOS Questions' started by Mashiane, May 27, 2015.

  1. Mashiane

    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?

    Code:
    Sub JsonToMap(strJSON As StringAs 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
     
  2. omidaghakhani1368

    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'}]
     
  3. Mashiane

    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 "'"

    Code:
    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
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice