iOS Code Snippet Map to JSON String

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

  1. Mashiane

    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...

    Code:
    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.

    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
     
    Last edited: May 29, 2015
    Molchyn likes this.
  2. Erel

    Erel Administrator Staff Member Licensed User

    This is not the correct way. You should use JsonGenerator from the iJSON library.
     
  3. Mashiane

    Mashiane Expert Licensed User

    Thanks Erel, will check that out ;)
     
    Erel likes this.
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