jump to navigation

Lotusscript : Json formatter… enjoy July 28, 2008

Posted by pierrekoerber in Lotus domino.
Tags: , , , , ,
trackback

Hello, the following class allows you to format easily your return to your AJAX requests in JSON.


'--------------------------------------------------
'Calling code
'--------------------------------------------------

Dim sJson As New cJSON

Call sJson.addItem("myParameter1", True)
Call sJson.addItem("myParameter2", "this is a value")
Call sJson.addItem("myNumericPara", 2324)
Call sJson.addItem("myJSONStruct", sJson)

Msgbox sJson.getJSONWithHeader()

————————————————–

Calling code

————————————————–

Dim sJson As New cJSON

Call sJson.addItem(”myParameter1″, True)
Call sJson.addItem(”myParameter2″, “this is a value”)
Call sJson.addItem(”myNumericPara”, 2324)
Call sJson.addItem(”myJSONStruct”, sJson)

Msgbox sJson.getJSONWithHeader()

————————————————–

class code

————————————————–
‘/**——————————————————————————————
‘ * Object         cJSON
‘ * @author         Pierre Koerber
‘ * @version         1.0 – 24.07.2008
‘ * History :
‘ */——————————————————————————————
Class cJSON
Private lstItem List As String
Private newLine As String

Sub new
newLine = Chr(13) & Chr(10)
End Sub

Public Function getRandomString() As String
getRandomString = Replace(Cstr(Rnd(1)), “.”, “”)
End Function

Public Function addItem(sName As Variant, vValue As Variant) As Variant
Dim sJson As String

sJson = |%1:%2|
sJson = Replace(sJson, “%1″, sName)

Select Case Typename(vValue)
Case “CJSON”:
sJson = Replace(sJson, “%2″, vValue.getJSON())
Case “STRING”
sJson = Replace(sJson, “%2″, |”| + Cstr(vValue) + |”|)
Case “BOOLEAN”
If vValue = True Then
sJson = Replace(sJson, “%2″, “true”)
Else
sJson = Replace(sJson, “%2″, “false”)
End If
Case Else
sJson = Replace(sJson, “%2″, Cstr(vValue))
End Select

lstItem(getRandomString) = sJson
End Function

Public Function getJSON() As String
Dim i As Integer
Dim sRes As String
i = 0
sRes = “{”
Forall x In  lstItem
If i=0 Then
sRes = sRes + x
Else
sRes = sRes + “,” + x
End If
i = i + 1
End Forall

getJSON = sRes + “}”
End Function

Public Function getJSONWithHeader() As String
Dim sRet As String
sRet = |Content-Type: text/javascript; charset=UTF-8| + newLine
sRet = sRet + |Cache-Control: no-cache| + newLine
sRet = sRet + getJSON()
getJSONWithHeader = sRet
End Function

End Class