cJson Best Practices and Tips
Usage Recommendations
1. Instance Selection
| Scenario | Recommended Approach | Description |
|---|---|---|
| Temporary use | With New cJson | Auto-cleanup after use |
| Need to persist | Dim Json As New cJson | Can be passed across methods |
| Global config | VBMAN.Json | Global shared, remember to clean |
Recommended Code:
vb
'Temporary use - recommended approach
With New VBMANLIB.cJson
.Item("key") = "value"
MsgBox .Encode()
End With
'Object auto-released, no manual cleanup needed2. Array Operation Notes
Important: Array index starts from 1!
vb
With Json.NewItems("items")
'Add elements using 0
.Items(0) = "First item"
.Items(0) = "Second item"
End With
'Access using 1-based index
MsgBox Json.Item("items")(1) 'First item
MsgBox Json.Item("items")(2) 'Second item3. Timely Cleaning of Global Instance
When using the VBMAN.Json global instance, remember to clean before starting:
vb
With VBMAN.Json
.Clear 'Important! Clean previous data
.Item("key") = "value"
'...
End With4. Naming Convention Recommendations
vb
'JSON key names recommended: camelCase or snake_case
Json.Item("userName") 'camelCase
Json.Item("user_name") 'snake_case
'Avoid Chinese key names (even though supported)
Json.Item("Username") 'Not recommended, may cause compatibility issuesPerformance Optimization
1. Large Batch Data Processing
vb
'Recommended: Estimate array size in advance if possible
Private Sub BatchProcess()
With New cJson
With .NewItems("records")
Dim Rs As ADODB.Recordset
Set Rs = GetData()
'Use With statement to reduce object lookup
Do While Not Rs.EOF
With .NewItem()
.Item("id") = Rs("id")
.Item("name") = Rs("name")
End With
Rs.MoveNext
Loop
End With
'Single output, avoid multiple Encode calls
Dim Result As String
Result = .Encode(, 0) 'Compact format saves space
End With
End Sub2. Chained Access vs. Layered Processing
Recommended: Chained Access (concise and clear):
vb
'Direct chained access to nested data
MsgBox Json.Root("user")("profile")("name")
MsgBox Json.Root("data")(1)("title")Only use layered processing when reusing sub-nodes:
vb
'When needing to use the same sub-node multiple times, layered is more efficient
Dim User As Object
Set User = Json.Root("user")
MsgBox User("name")
MsgBox User("email")
MsgBox User("profile")("age")Common Pitfalls
Pitfall 1: Forget to Check if Key Exists
vb
'Wrong: Directly access a key that may not exist
MsgBox Json.Item("mayNotExist") 'May error
'Correct: Check existence first
If Json.RootItem.Exists("mayNotExist") Then
MsgBox Json.Item("mayNotExist")
Else
MsgBox "Key does not exist"
End IfPitfall 2: Confuse Root, Item, and Items
vb
'Root - for reading data (default member, returns Object supporting chained access)
MsgBox Json.Root("key")
MsgBox Json.Root("level1")("level2") 'Chained access to nested object
'Item - for setting key-value pairs (has Let/Set)
Json.Item("key") = "value"
'Items - for arrays (Collection), Index=0 means append
Json.Items(0) = "value" 'Add element
MsgBox Json.Root("arr")(1) 'Access element (index starts from 1)
'Wrong examples:
Json.Item(1) = "value" 'Wrong! Item requires string key
Json.Items("key") 'Wrong! Items requires numeric indexPitfall 3: Collection Index Out of Bounds
vb
'Wrong: Assume collection has elements (cJson uses VB Collection for arrays)
MsgBox Json.Root("items")(1) 'Will error if collection is empty
'Correct: Check Count first
If Json.Root("items").Count > 0 Then
MsgBox Json.Root("items")(1)
End IfError Handling Best Practices
vb
Private Sub ProcessJson()
On Error GoTo ErrorHandler
Dim Json As New cJson
'Parse JSON
Json.Decode JsonText
If Not Json.LastSuccess Then
LogError "JSON parse failed: " & Json.LastError
Exit Sub
End If
'Check required fields
If Not ValidateRequiredFields(Json) Then
LogError "Missing required fields"
Exit Sub
End If
'Process data
ProcessData Json
Exit Sub
ErrorHandler:
LogError "Processing error: " & Err.Description
End Sub
Private Function ValidateRequiredFields(Json As cJson) As Boolean
ValidateRequiredFields = True
If Not Json.RootItem.Exists("code") Then
ValidateRequiredFields = False
Exit Function
End If
If Not Json.RootItem.Exists("data") Then
ValidateRequiredFields = False
Exit Function
End If
End FunctionHTTP Request Integration Recommendations
GET Request Handling
vb
Private Sub HandleGetRequest()
On Error Resume Next
With VBMAN.HttpClient.Fetch(ReqGet, "https://api.example.com/data").ReturnJson()
If .Item("code") <> 200 Then
MsgBox "Request failed: " & .Item("message")
Exit Sub
End If
'Process successful response
ProcessSuccessResponse .Item("data")
End With
If Err.Number <> 0 Then
MsgBox "Network error: " & Err.Description
End If
End SubPOST Request Handling
vb
Private Sub HandlePostRequest()
On Error GoTo ErrorHandler
'Construct request body
Dim Body As String
With New cJson
.Item("action") = "submit"
.Item("timestamp") = Now()
Body = .Encode()
End With
'Send request
With New cHttpClient
.SetRequestContentType JsonString
.SendPost "https://api.example.com/submit", Body
'Parse response
With .ReturnJson()
Select Case .Item("code")
Case 200
MsgBox "Submit successful"
Case 400
MsgBox "Parameter error: " & .Item("message")
Case 500
MsgBox "Server error"
Case Else
MsgBox "Unknown error: " & .Item("message")
End Select
End With
End With
Exit Sub
ErrorHandler:
Debug.Print "Error: " & Err.Description
End SubFile Operation Recommendations
Safe File Read/Write
vb
Private Sub SafeFileOperation()
Dim FilePath As String
FilePath = App.Path & "\data\config.json"
'Check if file exists (SaveTo will auto-create directories)
If Dir(FilePath) <> "" Then
'Backup old file
FileCopy FilePath, FilePath & ".bak"
End If
'Write new content (SaveTo internally calls ToolsFso.AutoMakeDir to create directories)
With New cJson
.Item("version") = "1.0"
.SaveTo FilePath, "UTF-8", 2, True
End With
End SubNote: The SaveTo method internally calls ToolsFso.AutoMakeDir to create directories, no need to manually create them.
Debug Tips
Using Formatted Output
vb
'Development stage: use formatted output
Debug.Print Json.Encode(, 2, True)
'Production environment: use compact format
ResponseText = Json.Encode()Recording Debug Information
vb
Private Sub LogJson(Json As cJson, Context As String)
Debug.Print "=== " & Context & " ==="
Debug.Print Json.Encode(, 2, True)
Debug.Print "========================"
End Sub