Skip to content

cJson 快速开始指南

1. 引入库

确保项目中已添加对 VBMAN 库的引用:

vb
'在代码中使用以下方式引用
Dim Json As New VBMANLIB.cJson
'或者直接使用 VBMAN 全局实例
With VBMAN.Json
    '...
End With

2. 创建 JSON 对象

2.1 创建简单的键值对对象

vb
Private Sub CreateSimpleJson()
    With New VBMANLIB.cJson
        '直接赋值创建键值对
        .Item("servicesn") = "0001"
        .Item("userid") = "admin"
        .Item("token") = ""
        .Item("argcounts") = 2

        '编码为 JSON 字符串
        Dim JsonString As String
        JsonString = .Encode(, 2, True)

        Debug.Print JsonString
    End With
End Sub

输出结果:

json
{
  "servicesn": "0001",
  "userid": "admin",
  "token": "",
  "argcounts": 2
}

2.2 创建嵌套对象

vb
Private Sub CreateNestedJson()
    With New VBMANLIB.cJson
        .Item("name") = "张三"
        .Item("age") = 25

        '创建嵌套对象(使用 NewItem)
        With .NewItem("address")
            .Item("city") = "北京"
            .Item("district") = "海淀区"
        End With

        Debug.Print .Encode(, 2, True)
    End With
End Sub

输出结果:

json
{
  "name": "张三",
  "age": 25,
  "address": {
    "city": "北京",
    "district": "海淀区"
  }
}

2.3 创建数组

vb
Private Sub CreateArrayJson()
    With New VBMANLIB.cJson
        .Item("code") = 200
        .Item("msg") = "成功"

        '创建数组(使用 NewItems)
        With .NewItems("data")
            '添加数组元素(使用 NewItem 创建对象元素)
            With .NewItem()
                .Item("id") = 1
                .Item("name") = "项目1"
            End With
            With .NewItem()
                .Item("id") = 2
                .Item("name") = "项目2"
            End With
        End With

        Debug.Print .Encode(, 2, True)
    End With
End Sub

输出结果:

json
{
  "code": 200,
  "msg": "成功",
  "data": [
    { "id": 1, "name": "项目1" },
    { "id": 2, "name": "项目2" }
  ]
}

3. 解析 JSON 字符串

3.1 解析简单对象(使用 Root 访问)

vb
Private Sub ParseSimpleJson()
    Dim JsonText As String
    JsonText = "{""name"":""张三"",""age"":25,""city"":""北京""}"

    With New VBMANLIB.cJson
        .Decode JsonText

        '使用 Root 访问 - 推荐方式(返回 Object,支持链式访问)
        Debug.Print .Root("name")  '输出:张三
        Debug.Print .Root("age")   '输出:25
        Debug.Print .Root("city")  '输出:北京

        '或使用默认成员特性(更简洁)
        Debug.Print $("name")      '输出:张三
    End With
End Sub

3.2 解析嵌套对象和数组(使用 Root 链式访问)

vb
Private Sub ParseComplexJson()
    Dim JsonText As String
    JsonText = "{""code"":200,""data"":[{""id"":1,""name"":""项目1""},{""id"":2,""name"":""项目2""}]}"

    With New VBMANLIB.cJson
        .Decode JsonText

        '使用 Root 访问顶层字段
        Debug.Print .Root("code")  '输出:200

        '使用 Root 链式访问数组元素(注意:下标从 1 开始)
        Debug.Print .Root("data")(1)("name")  '输出:项目1
        Debug.Print .Root("data")(2)("name")  '输出:项目2

        '循环遍历数组(使用 Root)
        Dim Item As Variant
        For Each Item In .Root("data")
            Debug.Print Item("id") & " - " & Item("name")
        Next
    End With
End Sub

4. 文件操作

4.1 保存 JSON 到文件

vb
Private Sub SaveJsonToFile()
    With VBMAN.Json
        .Item("name") = "测试数据"
        .Item("version") = "1.0"

        '保存到文件(参数:路径, 编码, 缩进, 中文原样显示)
        .SaveTo "C:\tmp\data.json", "UTF-8", 2, True

        MsgBox "文件已保存"
    End With
End Sub

4.2 从文件加载 JSON

vb
Private Sub LoadJsonFromFile()
    With New VBMANLIB.cJson
        '从文件加载
        .LoadFrom "C:\tmp\data.json", "UTF-8"

        '使用数据(使用 Root 访问)
        MsgBox .Root("name")
    End With

    '或者直接使用(Root 是默认成员)
    MsgBox VBMAN.Json.LoadFrom("C:\tmp\data.json")("name")
End Sub

5. 与 HTTP 请求结合使用

5.1 发送 JSON 数据(POST 请求)

vb
Private Sub PostJsonData()
    '构造请求体
    Dim Body As String
    With New cJson
        .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
        Body = .Encode()
    End With

    '发送请求
    With New cHttpClient
        .RequestHeaders.Add "Content-Type", "application/json"
        Dim Response As String
        Response = .Fetch(ReqPost, "https://api.example.com/submit", Body).ReturnText()
        Debug.Print Response
    End With
End Sub

5.2 解析返回的 JSON 数据

vb
Private Sub ParseApiResponse()
    With VBMAN.HttpClient.Fetch(ReqGet, "https://api.example.com/data").ReturnJson()
        '格式化显示返回内容
        Text1.Text = .Encode(, 2, True)

        '提取数据
        If .Item("code") = 200 Then
            Dim Item As Variant
            For Each Item In .Item("data")
                List1.AddItem Item("name")
            Next
        Else
            MsgBox .Item("message")
        End If
    End With
End Sub

6. 常见错误处理

vb
Private Sub SafeJsonOperation()
    On Error GoTo ErrorHandler

    Dim Json As New cJson

    '解析可能格式错误的 JSON
    Json.Decode Text1.Text

    '检查解析是否成功
    If Json.LastSuccess Then
        MsgBox "解析成功: " & Json.Item("name")
    Else
        MsgBox "解析失败: " & Json.LastError
    End If

    Exit Sub

ErrorHandler:
    MsgBox "操作出错: " & Err.Description
End Sub

下一步

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