Skip to content

cJson 最佳实践与注意事项

使用建议

1. 实例选择

场景推荐方式说明
临时使用With New cJson用完即弃,自动清理
需要保存状态Dim Json As New cJson可在多个方法间传递
全局配置VBMAN.Json全局共享,注意清理

推荐代码:

vb
'临时使用推荐这种方式
With New VBMANLIB.cJson
    .Item("key") = "value"
    MsgBox .Encode()
End With
'对象自动释放,无需手动清理

2. 数组操作注意事项

重要:数组下标从 1 开始!

vb
With Json.NewItems("items")
    '添加元素使用 0
    .Items(0) = "第一项"
    .Items(0) = "第二项"
End With

'访问时使用 1-based 索引
MsgBox Json.Item("items")(1)  '第一项
MsgBox Json.Item("items")(2)  '第二项

3. 及时清理全局实例

使用 VBMAN.Json 全局实例时,注意在开始前清理:

vb
With VBMAN.Json
    .Clear  '重要!清理之前的数据

    .Item("key") = "value"
    '...
End With

4. 命名规范建议

vb
'JSON 键名建议使用驼峰或下划线命名
Json.Item("userName")     '驼峰式
Json.Item("user_name")    '下划线式

'避免使用中文键名(虽然支持)
Json.Item("用户名")        '不推荐,可能引起兼容问题

性能优化

1. 大批量数据处理

vb
'推荐:预先估算数组大小(如果有)
Private Sub BatchProcess()
    With New cJson
        With .NewItems("records")
            Dim Rs As ADODB.Recordset
            Set Rs = GetData()

            '使用 With 语句减少对象查找
            Do While Not Rs.EOF
                With .NewItem()
                    .Item("id") = Rs("id")
                    .Item("name") = Rs("name")
                End With
                Rs.MoveNext
            Loop
        End With

        '一次性输出,避免多次 Encode
        Dim Result As String
        Result = .Encode(, 0)  '紧凑格式节省空间
    End With
End Sub

2. 链式访问 vs 分层处理

推荐链式访问(简洁清晰):

vb
'直接链式访问嵌套数据
MsgBox Json.Root("user")("profile")("name")
MsgBox Json.Root("data")(1)("title")

需要重复使用子节点时,才分层处理

vb
'当需要多次使用同一子节点时,分层更高效
Dim User As Object
Set User = Json.Root("user")

MsgBox User("name")
MsgBox User("email")
MsgBox User("profile")("age")

常见陷阱

陷阱 1:忘记检查键是否存在

vb
'错误:直接访问可能不存在的键
MsgBox Json.Item("mayNotExist")  '可能出错

'正确:先检查是否存在
If Json.RootItem.Exists("mayNotExist") Then
    MsgBox Json.Item("mayNotExist")
Else
    MsgBox "键不存在"
End If

陷阱 2:混淆 Root、Item 和 Items

vb
'Root - 用于读取数据(默认成员,返回 Object 支持链式访问)
MsgBox Json.Root("key")
MsgBox Json.Root("level1")("level2")  '链式访问嵌套对象

'Item - 用于设置键值对(有 Let/Set)
Json.Item("key") = "value"

'Items - 用于数组(集合),Index=0 表示添加
Json.Items(0) = "value"  '添加元素
MsgBox Json.Root("arr")(1)  '访问元素(下标从1开始)

'错误示范:
Json.Item(1) = "value"   '错误!Item 需要字符串键
Json.Items("key")        '错误!Items 需要数字索引

陷阱 3:集合索引越界

vb
'错误:假设集合有元素(cJson 使用 VB Collection 存储数组)
MsgBox Json.Root("items")(1)  '如果集合为空会出错

'正确:先检查 Count
If Json.Root("items").Count > 0 Then
    MsgBox Json.Root("items")(1)
End If

错误处理最佳实践

vb
Private Sub ProcessJson()
    On Error GoTo ErrorHandler

    Dim Json As New cJson

    '解析 JSON
    Json.Decode JsonText

    If Not Json.LastSuccess Then
        LogError "JSON 解析失败: " & Json.LastError
        Exit Sub
    End If

    '检查必需字段
    If Not ValidateRequiredFields(Json) Then
        LogError "缺少必需字段"
        Exit Sub
    End If

    '处理数据
    ProcessData Json

    Exit Sub

ErrorHandler:
    LogError "处理出错: " & 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 Function

HTTP 请求集成建议

GET 请求处理

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 "请求失败: " & .Item("message")
            Exit Sub
        End If

        '处理成功响应
        ProcessSuccessResponse .Item("data")
    End With

    If Err.Number <> 0 Then
        MsgBox "网络错误: " & Err.Description
    End If
End Sub

POST 请求处理

vb
Private Sub HandlePostRequest()
    On Error GoTo ErrorHandler

    '构造请求体
    Dim Body As String
    With New cJson
        .Item("action") = "submit"
        .Item("timestamp") = Now()
        Body = .Encode()
    End With

    '发送请求
    With New cHttpClient
        .SetRequestContentType JsonString
        .SendPost "https://api.example.com/submit", Body

        '解析响应
        With .ReturnJson()
            Select Case .Item("code")
                Case 200
                    MsgBox "提交成功"
                Case 400
                    MsgBox "参数错误: " & .Item("message")
                Case 500
                    MsgBox "服务器错误"
                Case Else
                    MsgBox "未知错误: " & .Item("message")
            End Select
        End With
    End With

    Exit Sub

ErrorHandler:
    Debug.Print "错误: " & Err.Description
End Sub

文件操作建议

安全的文件读写

vb
Private Sub SafeFileOperation()
    Dim FilePath As String
    FilePath = App.Path & "\data\config.json"

    '检查文件是否存在(SaveTo 会自动创建目录)
    If Dir(FilePath) <> "" Then
        '备份旧文件
        FileCopy FilePath, FilePath & ".bak"
    End If

    '写入新内容(SaveTo 内部会自动创建目录)
    With New cJson
        .Item("version") = "1.0"
        .SaveTo FilePath, "UTF-8", 2, True
    End With
End Sub

注意: SaveTo 方法内部会自动调用 ToolsFso.AutoMakeDir 创建目录,无需手动创建。

调试技巧

使用格式化输出

vb
'开发阶段使用格式化输出
Debug.Print Json.Encode(, 2, True)

'生产环境使用紧凑格式
ResponseText = Json.Encode()

记录调试信息

vb
Private Sub LogJson(Json As cJson, Context As String)
    Debug.Print "=== " & Context & " ==="
    Debug.Print Json.Encode(, 2, True)
    Debug.Print "========================"
End Sub

VB6及其LOGO版权为微软公司所有