Skip to content

cJson API 参考手册

核心概念

VB 类型与 JSON 对应关系

VB 类型JSON 类型说明
Dictionary(字典){ "key": "value" } 对象键值对结构
Collection(集合)[ 1, 2, 3 ] 数组有序列表

核心成员分工

成员主要用途说明
NewItem创建子对象节点创建 Dictionary 类型子节点,对应 JSON 对象 {...}
NewItems创建子数组节点创建 Collection 类型子节点,对应 JSON 数组 [...]
Item设置/读取对象成员在当前节点(Dictionary)上设置/获取键值对
Items设置/读取数组成员在当前节点(Collection)上设置/获取数组元素
Root链式读取返回根节点 Object,支持链式访问

构建 JSON 的正确流程

vb
'1. 创建根节点(本身就是对象节点)
With New cJson
    '在根节点上用 Item 设置键值对
    .Item("name") = "张三"
    .Item("age") = 25

    '2. 创建子数组节点(用 NewItems)
    With .NewItems("hobbies")  '创建名为 "hobbies" 的子数组
        '在子数组上用 Items 添加元素
        .Items(0) = "阅读"      'Index=0 表示添加
        .Items(0) = "编程"
    End With

    '3. 创建子对象节点(用 NewItem)
    With .NewItem("address")   '创建名为 "address" 的子对象
        '在子对象上用 Item 设置键值对
        .Item("city") = "北京"
        .Item("zip") = "100000"
    End With

    '4. 编码为 JSON 字符串
    Dim JsonString As String
    JsonString = .Encode()
    '输出:{"name":"张三","age":25,"hobbies":["阅读","编程"],"address":{"city":"北京","zip":"100000"}}
End With

属性列表

公共属性

属性名类型说明
RootObject默认成员,返回根节点对象(Dictionary/字典 或 Collection/集合),最常用
SelfcJson返回对象自身实例(Me),用于需要传递本对象的场景
RootTextString最后一次编码/解码的 JSON 文本
RootItemScripting.Dictionary根节点字典对象,对应 JSON 对象 { ... }
RootItemsCollection根节点集合对象,对应 JSON 数组 [ ... ]
LastErrorString最后一次错误信息
WhiteSpaceSetVariant全局缩进设置

类型对应关系:

  • Dictionary(字典) → JSON 对象 { "key": "value" }(有键值对)
  • Collection(集合) → JSON 数组 [ 1, 2, 3 ](有序列表)

状态属性

LastSuccess

vb
Public Property Get LastSuccess() As Boolean

返回最后一次操作是否成功(LastError = "" 时返回 True)。

示例:

vb
Json.Decode JsonText
If Json.LastSuccess Then
    MsgBox "解析成功"
Else
    MsgBox "解析失败: " & Json.LastError
End If

Root(默认成员,用于链式读写)

vb
Public Property Get Root() As Object
Attribute Root.VB_UserMemId = 0

返回根节点对象。如果 RootItems.Count > 0 返回 Collection(集合/数组),否则返回 Dictionary(字典/对象)

重要特性:

  • 默认成员Root 是类的默认成员,可直接用 Json("key") 访问,等同于 Json.Root("key")
  • 返回 Object:返回 Dictionary(对应 JSON 对象 {...})或 Collection(对应 JSON 数组 [...]),支持链式嵌套访问
  • 用于链式读写:读取嵌套 JSON 数据时推荐使用 Root,支持无限层级链式访问
  • 类型对应
    • Dictionary → JSON 对象 { "key": "value" }
    • Collection → JSON 数组 [ 1, 2, 3 ]

示例:

vb
'直接访问(利用默认成员特性)
MsgBox Json("name")                    '等同于 Json.Root("name")
MsgBox Json("user")("name")            '链式访问嵌套对象
MsgBox Json("items")(1)("title")       '访问数组内对象(数组下标从1开始)

'明确使用 Root 属性
MsgBox Json.Root("name")
MsgBox Json.Root("user")("name")

'遍历数组
Dim Item As Variant
For Each Item In Json("data")
    Debug.Print Item("name")
Next

RootIsEmpty

vb
Public Property Get RootIsEmpty() As Boolean

检查根节点是否为空(没有键值对也没有数组元素)。

示例:

vb
If Json.RootIsEmpty Then
    MsgBox "JSON 对象为空"
End If

RootIsArray

vb
Public Property Get RootIsArray() As Boolean

检查根节点是否为数组类型。

示例:

vb
If Json.RootIsArray Then
    MsgBox "根节点是数组"
End If

数据访问属性

Item(在当前对象节点上增改成员)

vb
Public Property Get Item(ByVal Key As String) As Variant
Public Property Let Item(ByVal Key As String, Dat As Variant)
Public Property Set Item(ByVal Key As String, Dat As Variant)

在当前对象节点(Dictionary)上访问或设置键值对。

核心作用:

  • 增改对象成员:在当前对象节点上设置键值对,用于构建 JSON 对象的属性
  • 适用节点:只能在 Dictionary 类型节点上使用(包括根节点和 NewItem 创建的子对象)
  • 对应 JSON:操作的是 Dictionary,对应 JSON 对象 { "key": "value" }

参数:

  • Key - 键名(字符串)
  • Dat - 要设置的值(任意类型)

使用场景:

  1. 根节点上设置键值对(根节点默认是对象)
  2. NewItem 创建的子对象 上设置键值对

示例:

vb
'===== 场景1:在根节点上设置键值对 =====
With New cJson
    '根节点本身就是对象,直接用 Item
    .Item("name") = "张三"
    .Item("age") = 25
    .Item("active") = True
    '结果:{ "name": "张三", "age": 25, "active": true }
End With

'===== 场景2:在 NewItem 创建的子对象上设置 =====
With New cJson
    '创建子对象 "address"
    With .NewItem("address")
        '在子对象上用 Item 设置键值对
        .Item("city") = "北京"
        .Item("zip") = "100000"
    End With
    '结果:{ "address": { "city": "北京", "zip": "100000" } }
End With

'===== 读取值(推荐用 Root 链式访问)=====
'不推荐:Item 返回 Variant,不支持链式访问
Name = Json.Item("name")

'推荐:Root 返回 Object,支持链式访问
Name = Json.Root("name")
City = Json.Root("address")("city")  '链式访问嵌套对象

'设置对象引用
Dim SubJson As New cJson
Set Json.Item("sub") = SubJson.Root

Items(在当前数组节点上增改成员)

vb
Public Property Get Items(ByVal Index As Long) As Variant
Public Property Let Items(ByVal Index As Long, Dat As Variant)
Public Property Set Items(ByVal Index As Long, Dat As Variant)

在当前数组节点(Collection)上访问或设置数组元素。注意:索引从 1 开始

核心作用:

  • 增改数组成员:在当前数组节点上添加或修改数组元素
  • 适用节点:只能在 Collection 类型节点上使用(NewItems 创建的子数组)
  • 对应 JSON:操作的是 Collection,对应 JSON 数组 [ 1, 2, 3 ]

参数:

  • Index - 数组索引(从 1 开始)
  • Dat - 要设置的值

特殊用法:

  • Index = 0 时,表示添加新元素到数组末尾

使用场景:

  1. NewItems 创建的子数组 上添加元素

示例:

vb
'===== 场景:在 NewItems 创建的子数组上添加元素 =====
With New cJson
    With .NewItems("tags")  '创建名为 "tags" 的子数组
        '在子数组上用 Items 添加元素
        .Items(0) = "VIP"       'Index=0 表示添加
        .Items(0) = "活跃"
        .Items(0) = "付费"
    End With
    '结果:{ "tags": ["VIP", "活跃", "付费"] }

    '数组中的对象元素
    With .NewItems("users")
        With .NewItem()         '数组第一个对象元素
            .Item("name") = "张三"
            .Item("age") = 25
        End With
        With .NewItem()         '数组第二个对象元素
            .Item("name") = "李四"
            .Item("age") = 30
        End With
    End With
    '结果:{ "users": [{"name":"张三","age":25}, {"name":"李四","age":30}] }
End With

'===== 访问数组元素(用 Root,从 1 开始)=====
Dim First As String
First = Json.Root("tags")(1)  'VIP

'修改数组元素
Json.Root("tags").Items(1) = "新值"

'遍历数组(推荐用 Root)
Dim Item As Variant
For Each Item In Json.Root("tags")
    Debug.Print Item
Next

'修改数组元素
Json.Items(1) = "新值"

方法列表

Clear

vb
Public Sub Clear()

清空所有数据,重置对象状态。

示例:

vb
Json.Item("name") = "张三"
Json.Clear
'现在 Json.RootIsEmpty = True

NewItem(创建子对象节点)

vb
Public Function NewItem(Optional ParentKey As String) As cJson

创建一个新的 Dictionary 类型子节点,对应 JSON 对象 { ... }

核心作用:

  • 创建子对象:在当前节点下创建一个子对象(Dictionary)节点
  • 对应 JSON:创建的是 JSON 对象 { "key": "value" }
  • 后续操作:创建后使用 Item 在该子对象上设置键值对

参数:

  • ParentKey - 父节点中的键名(可选)
    • 提供键名:子对象挂载到父节点的该键下
    • 省略键名:子对象添加到父节点的数组中(父节点必须是数组类型)

返回:

  • 新创建的 cJson 实例(Dictionary 类型)

使用流程:

  1. 调用 NewItem([Key]) 创建子对象
  2. 在返回的 cJson 实例上用 Item 设置键值对

示例:

vb
'===== 场景1:创建具名子对象(带 ParentKey)=====
With New cJson
    '创建名为 "address" 的子对象
    With .NewItem("address")
        '在子对象上用 Item 设置键值对
        .Item("city") = "北京"
        .Item("zip") = "100000"
    End With
    '结果:{ "address": { "city": "北京", "zip": "100000" } }
End With

'===== 场景2:创建数组中的对象元素(省略 ParentKey)=====
With New cJson
    With .NewItems("users")      '先创建数组 "users"
        With .NewItem()           '创建数组第一个对象元素
            .Item("name") = "张三"
            .Item("age") = 25
        End With
        With .NewItem()           '创建数组第二个对象元素
            .Item("name") = "李四"
            .Item("age") = 30
        End With
    End With
    '结果:{ "users": [{"name":"张三","age":25}, {"name":"李四","age":30}] }
End With

'===== 场景3:无限层级嵌套 =====
With New cJson
    With .NewItem("level1")
        With .NewItem("level2")
            With .NewItem("level3")
                .Item("value") = "深层数据"
            End With
        End With
    End With
    '结果:{ "level1": { "level2": { "level3": { "value": "深层数据" } } } }
End With

NewItems(创建子数组节点)

vb
Public Function NewItems(Optional ParentKey As String) As cJson

创建一个新的 Collection 类型子节点,对应 JSON 数组 [ ... ]

核心作用:

  • 创建子数组:在当前节点下创建一个子数组(Collection)节点
  • 对应 JSON:创建的是 JSON 数组 [ 1, 2, 3 ]
  • 后续操作:创建后使用 Items 在该子数组上添加元素,或使用 NewItem 添加对象元素

参数:

  • ParentKey - 父节点中的键名(可选)
    • 提供键名:子数组挂载到父节点的该键下
    • 省略键名:子数组添加到父节点的数组中(父节点必须是数组类型)

返回:

  • 新创建的 cJson 实例(Collection 类型)

使用流程:

  1. 调用 NewItems([Key]) 创建子数组
  2. 在返回的 cJson 实例上:
    • Items(0) 添加普通值元素
    • NewItem() 添加对象元素

示例:

vb
'===== 场景1:创建具名子数组(带 ParentKey)=====
With New cJson
    '创建名为 "tags" 的子数组
    With .NewItems("tags")
        '在子数组上用 Items 添加元素
        .Items(0) = "VIP"       'Index=0 表示添加
        .Items(0) = "活跃"
        .Items(0) = "付费"
    End With
    '结果:{ "tags": ["VIP", "活跃", "付费"] }
End With

'===== 场景2:创建数组中的数组(省略 ParentKey)=====
With New cJson
    With .NewItems("matrix")     '创建二维数组
        With .NewItems()          '第一行数组
            .Items(0) = 1
            .Items(0) = 2
        End With
        With .NewItems()          '第二行数组
            .Items(0) = 3
            .Items(0) = 4
        End With
    End With
    '结果:{ "matrix": [[1, 2], [3, 4]] }
End With

'===== 场景3:对象数组(混合使用 NewItem 和 Items)=====
With New cJson
    With .NewItems("users")
        '数组元素是对象:用 NewItem 创建,用 Item 设置
        With .NewItem()
            .Item("name") = "张三"
            .Item("age") = 25
        End With
        '再添加一个对象
        With .NewItem()
            .Item("name") = "李四"
            .Item("age") = 30
        End With
    End With
    '结果:{ "users": [{"name":"张三","age":25}, {"name":"李四","age":30}] }
End With

Encode

vb
Public Function Encode( _
    Optional Obj As Variant, _
    Optional Whitespace As Variant, _
    Optional FromUnicode As Boolean _
) As String

将对象编码为 JSON 字符串。

参数:

  • Obj - 要编码的对象(可选,省略时使用内部 RootItem/RootItems)
  • Whitespace - 格式化缩进(数字表示空格数,字符串表示缩进字符)
  • FromUnicode - 是否将 Unicode 编码解码为中文(True 显示中文)

返回:

  • JSON 字符串

示例:

vb
'简单编码
Dim JsonStr As String
JsonStr = Json.Encode()

'格式化输出(2个空格缩进)
JsonStr = Json.Encode(, 2)

'格式化并显示中文
JsonStr = Json.Encode(, 2, True)

'编码指定对象
JsonStr = Json.Encode(Json.Item("subObject"), 2, True)

Decode

vb
Public Function Decode(ByRef Text As String) As cJson

解析 JSON 字符串为对象。支持 JSONP 格式和 var 变量格式

参数:

  • Text - 要解析的 JSON 字符串

返回:

  • 返回自身实例(支持链式调用)

支持格式:

  • 标准 JSON: {"name": "value"}
  • JSON 数组: [{"name": "value"}]
  • JSONP: callback({"name": "value"});
  • Var 变量: var data = {"name": "value"};

示例:

vb
'标准 JSON
Json.Decode "{""name"":""张三""}"

'JSONP 格式(自动提取)
Json.Decode "callback({""name"":""张三""});"

'Var 格式(自动提取)
Json.Decode "var data = {""name"":""张三""};"

'链式调用
MsgBox Json.Decode(JsonText).Item("name")

LoadFrom

vb
Public Function LoadFrom(ByVal Path As String, _
    Optional CharSet As String = "UTF-8" _
) As cJson

从文件加载 JSON 数据。

参数:

  • Path - 文件路径
  • CharSet - 字符编码(默认 UTF-8)

返回:

  • 返回自身实例(支持链式调用)

示例:

vb
'从文件加载
Json.LoadFrom "C:\data.json"

'指定编码
Json.LoadFrom "C:\data.json", "GB2312"

'链式调用
MsgBox Json.LoadFrom("C:\data.json").Item("name")

SaveTo

vb
Public Function SaveTo( _
    ByVal FileName As String, _
    Optional CharSet As String = "UTF-8", _
    Optional Whitespace As Variant, _
    Optional FromUnicode As Boolean _
) As String

将 JSON 数据保存到文件。

参数:

  • FileName - 文件路径
  • CharSet - 字符编码(默认 UTF-8)
  • Whitespace - 格式化缩进
  • FromUnicode - 是否显示中文

返回:

  • 保存的 JSON 字符串内容

示例:

vb
'简单保存
Json.SaveTo "C:\data.json"

'格式化保存
Json.SaveTo "C:\data.json", "UTF-8", 2, True

ToArray

vb
Public Function ToArray() As Variant

将 JSON 数据转换为 VB 数组。

示例:

vb
Dim Arr As Variant
Arr = Json.ToArray()

内部函数(Private)

以下函数是内部使用的,不对外公开:

ConvertToJson

内部使用,将 VB 对象转换为 JSON 字符串(来自 VBA-JSON)。

ParseJson

内部使用,解析 JSON 字符串为 VB 对象(来自 VBA-JSON)。

使用技巧

链式访问深层数据

vb
'多层嵌套访问
MsgBox Json.Item("level1")("level2")("level3")

'数组访问(下标从 1 开始)
MsgBox Json.Item("users")(1)("name")

安全的值获取

vb
'检查键是否存在(使用 RootItem)
If Json.RootItem.Exists("key") Then
    Value = Json.Item("key")
End If

'获取数组长度
Dim Count As Long
Count = Json.Item("array").Count

循环遍历数组

vb
'For Each 遍历
Dim Item As Variant
For Each Item In Json.Item("data")
    Debug.Print Item("name")
Next

'For 循环遍历(下标从 1 开始)
Dim i As Long
For i = 1 To Json.Item("data").Count
    Debug.Print Json.Item("data")(i)("name")
Next

类型转换注意事项

vb
'数字转字符串
Dim StrValue As String
StrValue = CStr(Json.Item("numberField"))

'字符串转数字
Dim NumValue As Long
NumValue = CLng(Json.Item("stringField"))

'日期处理
Dim DateValue As Date
DateValue = CDate(Json.Item("dateField"))

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