cJson Code Examples
This document contains detailed example code for various practical usage scenarios.
Table of Contents
Basic Examples
Example 1: Creating a User Info Object
Private Sub CreateUserInfo()
With New VBMANLIB.cJson
.Item("username") = "admin"
.Item("password") = "123456"
.Item("age") = 40
.Item("name") = "Deng Wei"
'Formatted output, display Chinese
Debug.Print .Encode(, 2, True)
End With
End SubOutput:
{
"username": "admin",
"password": "123456",
"age": 40,
"name": "Deng Wei"
}Example 2: Creating JSON with an Array
Private Sub CreateWithArray()
With New VBMANLIB.cJson
.Item("code") = 200
.Item("msg") = "Success"
'Create plain value array
With .NewItems("hobbies")
.Items(0) = "Reading"
.Items(0) = "Swimming"
.Items(0) = "Coding"
End With
Debug.Print .Encode(, 2, True)
End With
End SubOutput:
{
"code": 200,
"msg": "Success",
"hobbies": ["Reading", "Swimming", "Coding"]
}Example 3: Parsing and Reading JSON
Private Sub ParseAndRead()
Dim JsonText As String
JsonText = "{""servicesn"":""0001"",""userid"":""admin"",""token"":"""",""argcounts"":2}"
With New VBMANLIB.cJson
.Decode JsonText
'Read fields using Root (recommended approach)
Debug.Print "Service SN: " & .Root("servicesn")
Debug.Print "User ID: " & .Root("userid")
Debug.Print "Token: " & .Root("token")
Debug.Print "Arg Counts: " & .Root("argcounts")
End With
End SubHTTP API Interaction
Example 4: Constructing a POST Request Body
Method 1: Using an independent cJson instance (recommended for complex structures)
Private Sub BuildPostBody()
Dim Body As String
'Create independent JSON object
With New cJson
.Item("sysStuffCode") = "TEST001"
.Item("quantity") = 2
'Construct array
With .NewItems("detailList")
Dim i As Long
For i = 0 To 3
With .NewItem()
.Item("test") = 123
.Item("time") = Now()
End With
Next
End With
Body = .Encode()
End With
'Send request
With New cHttpClient
.RequestHeaders.Add "Content-Type", "application/json"
.Fetch ReqPost, "https://api.example.com/submit", Body
Debug.Print .ReturnText()
End With
End SubMethod 2: Using HttpClient's built-in RequestDataJson object (concise approach)
Private Sub BuildPostBodySimple()
With VBMAN.HttpClient
'Use built-in RequestDataJson object to construct request body
With .RequestDataJson
.Clear 'Clear previous data
.Item("sysStuffCode") = "TEST001"
.Item("quantity") = 2
With .NewItems("detailList")
Dim i As Long
For i = 0 To 3
With .NewItem()
.Item("test") = 123
.Item("time") = Now()
End With
Next
End With
End With
'Set request type and send (ContentType=Json auto-uses RequestDataJson)
.SetRequestContentType JsonString
.SendPost "https://api.example.com/submit" 'Body parameter can be omitted, auto-uses RequestDataJson
Debug.Print .ReturnText()
End With
End SubExample 5: Handling API Response
Private Sub HandleApiResponse()
Const API_BASE As String = "https://api.example.com"
Const API_PULL_WAYBILL As String = API_BASE & "/api/pullWaybill"
'Construct request data
Dim Body As String
With New cJson
.Item("wayBillId") = "46349936"
.Item("clientId") = "CLIENT001"
.Item("token") = "cbe84888-9f48-4c00-aae6-3170bf5951cd"
Body = .Encode()
End With
'Send request and handle response
On Error GoTo ErrorHandler
With VBMAN.HttpClient
.SetRequestContentType JsonString
.SendPost API_PULL_WAYBILL, Body
With .ReturnJson()
'Display full response
Text2.Text = .Encode(, 2, True)
'Check business status
If .Root("success") = True Then
MsgBox "Cargo Name: " & .Root("data")("cargoName"), , "Waybill No: " & .Root("data")("wayBillId")
Else
MsgBox .Root("message"), , "Request Failed"
End If
End With
End With
Exit Sub
ErrorHandler:
Debug.Print VBMAN.HttpClient.DebugInfo.Encode(, 2, True)
End SubExample 6: Fetching Data with Query Parameters
Private Sub FetchWithQuery()
Const API_BASE As String = "https://api.example.com"
Const API_SALE_PLAN As String = API_BASE & "/api/salePlan/selectByVehicleNo"
On Error Resume Next
'Use built-in query builder (auto URL-encode)
VBMAN.HttpClient.RequestDataQuery.Add "vehicleNo", "鲁B70AP0"
With VBMAN.HttpClient.Fetch(ReqGet, API_SALE_PLAN).ReturnJson()
'Display formatted result
Text1.Text = .Encode(, 2, True)
'Check return status (using Root access)
If .Root("code") = 200 Then
'Loop through array
Dim x As Variant
For Each x In .Root("data")
List1.AddItem x("planCode")
List1.AddItem x("warehouseName")
Next
'Directly get specific array object (using Root chained access)
With .Root("data")(1)
List1.AddItem .Root("planCode")
List1.AddItem .Root("warehouseName")
End With
Else
MsgBox .Root("message")
End If
End With
End SubFile Operations
Example 7: Saving Configuration to a JSON File
Private Sub SaveConfig()
With VBMAN.Json
'Clear previous data
.Clear
.Item("appName") = "MyApplication"
.Item("version") = "1.0.0"
.Item("debug") = True
'Nested config object
With .NewItem("database")
.Item("host") = "localhost"
.Item("port") = 3306
.Item("username") = "root"
.Item("password") = "secret"
End With
'Save to file
.SaveTo App.Path & "\config.json", "UTF-8", 2, True
MsgBox "Configuration saved"
End With
End SubExample 8: Loading Configuration from a JSON File
Private Sub LoadConfig()
Dim ConfigPath As String
ConfigPath = App.Path & "\config.json"
'Check if file exists
If Dir(ConfigPath) = "" Then
MsgBox "Configuration file does not exist"
Exit Sub
End If
With New VBMANLIB.cJson
.LoadFrom ConfigPath
'Read configuration
Dim AppName As String
Dim DbHost As String
Dim DbPort As Long
AppName = .Root("appName")
DbHost = .Root("database")("host")
DbPort = .Root("database")("port")
MsgBox "App: " & AppName & vbCrLf & _
"Database: " & DbHost & ":" & DbPort
End With
End SubExample 9: Loading from File and Modifying
Private Sub ModifyJsonFile()
Dim FilePath As String
FilePath = "C:\tmp\data.json"
With New VBMANLIB.cJson
.LoadFrom FilePath
'Modify data
.Item("name") = "New Name"
.Item("updated") = Now()
'Save back to file
.SaveTo FilePath, "UTF-8", 2, True
End With
End SubComplex Data Structures
Example 10: Unlimited Level Nesting
Private Sub NestedStructure()
With New VBMANLIB.cJson
.Item("a") = 1
.Item("b") = "dengwei"
With .NewItems("c")
Dim i As Long
For i = 0 To 3
With .NewItem()
.Item("d") = Now()
.Item("e") = 34 + i
.Item("f") = "Data: " & i
'Create deeper nesting
With .NewItem("g")
.Item("g1") = 123
.Item("g2") = 456
End With
With .NewItems("h")
.Items(0) = "Array element 1"
.Items(0) = "Array element 2"
End With
End With
Next
End With
'Save and display
.SaveTo "C:\tmp\nested.json", , 2, True
Text1.Text = .Encode(, 2, True)
End With
End SubExample 11: Mixed Array (Objects and Plain Values)
Private Sub MixedArray()
With New VBMANLIB.cJson
'Object array
With .NewItems("users")
With .NewItem()
.Item("name") = "John"
.Item("age") = 25
End With
With .NewItem()
.Item("name") = "Jane"
.Item("age") = 30
End With
End With
'Plain value array
With .NewItems("tags")
.Items(0) = "VIP"
.Items(0) = "Active"
.Items(0) = "Paid"
End With
Debug.Print .Encode(, 2, True)
End With
End SubOutput:
{
"users": [
{ "name": "John", "age": 25 },
{ "name": "Jane", "age": 30 }
],
"tags": ["VIP", "Active", "Paid"]
}Example 12: Parsing Complex Nested JSON
Private Sub ParseComplexNested()
'Assume this is complex JSON from an API
Dim JsonText As String
JsonText = "{"
JsonText = JsonText & """code"":200,"
JsonText = JsonText & """data"":{"
JsonText = JsonText & " ""company"":""ABC Corp"","
JsonText = JsonText & " ""departments"":[{"
JsonText = JsonText & " ""name"":""Engineering"","
JsonText = JsonText & " ""employees"":[{""name"":""John"",""position"":""Engineer""}]"
JsonText = JsonText & " }]"
JsonText = JsonText & "}"
JsonText = JsonText & "}"
With New VBMANLIB.cJson
.Decode JsonText
'Deep chained access using Root
Dim Company As String
Dim DeptName As String
Dim EmpName As String
Company = .Root("data")("company")
DeptName = .Root("data")("departments")(1)("name")
EmpName = .Root("data")("departments")(1)("employees")(1)("name")
MsgBox "Company: " & Company & vbCrLf & _
"Department: " & DeptName & vbCrLf & _
"Employee: " & EmpName
End With
End SubReal Business Scenarios
Example 13: User Login API (HTTP Server)
'In business class (e.g., bHello.cls)
Public Sub Login(ctx As cHttpServerContext)
Dim username As String: username = ctx.Request.Form("username")
Dim password As String: password = ctx.Request.Form("password")
With New cJson
.Item("name") = "Deng Wei"
.Item("age") = 40
.Item("username") = username
.Item("password") = password
'Return formatted JSON
ctx.Response.Text .Encode(, 2, True)
End With
End SubExample 14: SSE Data Push
'In timed send class (e.g., bSendData.cls)
Private Sub SendTotalData()
With New VBMANLIB.cJson
'Server time
With .NewItem()
.Item("id") = "serverTime"
.Item("value") = Format(Now(), "yyyy-MM-dd HH:mm:ss")
End With
'Statistics data
With .NewItem()
.Item("id") = "today_count"
.Item("value") = GetTodayCount()
End With
With .NewItem()
.Item("id") = "yesterday_count"
.Item("value") = GetYesterdayCount()
End With
'Send to frontend
Form1.HttpServer.SSE.SendPack "total", .Encode()
End With
End SubExample 15: Database Records to JSON
Method 1: Using RsToCollection function (Recommended)
VBMAN provides the global function VBMAN.ToolsList.RsToCollection, which can directly convert a Recordset to a Collection. Using it with cJson is simpler:
Private Sub RecordsToJsonEasy()
Dim Rs As ADODB.Recordset
Set Rs = GetRecords() 'Get database recordset
With New VBMANLIB.cJson
.Item("code") = 200
.Item("total") = Rs.RecordCount
'Directly assign converted collection
.Item("data") = VBMAN.ToolsList.RsToCollection(Rs)
ctx.Response.Text .Encode(, 2, True)
End With
End SubMethod 2: Manual iteration construction (for understanding principles)
Private Sub RecordsToJson()
Dim Rs As ADODB.Recordset
Set Rs = GetRecords() 'Get database recordset
With New VBMANLIB.cJson
.Item("code") = 200
.Item("total") = Rs.RecordCount
With .NewItems("data")
Do While Not Rs.EOF
With .NewItem()
.Item("id") = Rs("id")
.Item("name") = Rs("name")
.Item("created") = Rs("created_at")
End With
Rs.MoveNext
Loop
End With
'Output or save
ctx.Response.Text .Encode(, 2, True)
End With
End SubTip: The
RsToCollectionfunction is available globally viaVBMAN.ToolsList.RsToCollection. It automatically handles pagination and field mapping, making it the best practice for converting database records to JSON.
Example 16: Batch Task Data Structure
Private Function MakeTaskData() As String
With New cJson
'Root is an array, need NewItem first
With .NewItem()
.Item("uuid") = GenerateUUID()
.Item("task_no") = "TASK001"
.Item("task_type") = 1
.Item("factory_code") = "0206"
.Item("warehouse_code") = "0601"
'Detail array
With .NewItems("detail")
With .NewItem()
.Item("row_no") = 1
.Item("part_no") = "PART001"
.Item("qty") = 45.5
End With
With .NewItem()
.Item("row_no") = 2
.Item("part_no") = "PART002"
.Item("qty") = 30.0
End With
End With
End With
MakeTaskData = .Encode(.Root, 2)
End With
End FunctionExample 17: Dynamically Building Report Data
Private Sub BuildReportData()
With New VBMANLIB.cJson
.Item("ReportTime") = Format(Date, "yyyy-mm-dd")
.Item("SampleModel") = "Sample Model 123"
.Item("ProductModel") = "Product Model ABC"
Dim i As Long
For i = 1 To 10
With .NewItem("record" & i)
.Item("TestNum") = "TEST" & i
.Item("T1") = RandValue()
.Item("T2") = RandValue()
.Item("Result") = IIf(i Mod 2 = 0, "PASS", "FAIL")
End With
Next
'Save report
.SaveTo App.Path & "\Reports\" & Format(Now(), "yyyymmdd") & ".json", , 2, True
End With
End SubExample 18: Using Global Instance for Data Caching
Private Sub UseGlobalInstance()
'Use global VBMAN.Json instance to cache configuration
With VBMAN.Json
.Clear 'Clean first
.Item("api_url") = "https://api.example.com"
.Item("timeout") = 30
.Item("retry") = 3
'Can be used elsewhere directly (Root is default member)
'MsgBox VBMAN.Json.Root("api_url")
'Or shorthand:
'MsgBox VBMAN.Json("api_url")
End With
End SubDebug Tips
Example 19: Formatted Output for Debugging
Private Sub DebugJson()
With New VBMANLIB.cJson
'Build complex data...
.Item("data") = "Some data"
'Output to immediate window (formatted)
Debug.Print .Encode(, 2, True)
'Output to text box
Text1.Text = .Encode(, 2, True)
'Compact format (for transmission)
Debug.Print .Encode()
End With
End SubExample 20: Error Handling Pattern
Private Sub SafeParse()
On Error GoTo ErrorHandler
Dim Json As New cJson
Json.Decode Text1.Text
If Not Json.LastSuccess Then
MsgBox "JSON parse failed: " & Json.LastError
Exit Sub
End If
'Safe data access
If Json.RootItem.Exists("name") Then
MsgBox "Name: " & Json.Item("name")
Else
MsgBox "name field does not exist"
End If
Exit Sub
ErrorHandler:
MsgBox "Error occurred: " & Err.Number & " - " & Err.Description
End Sub