VBMAN.Json - JSON 操作对象
概述
VBMAN.Json 提供了 JSON 数据的解析和生成功能,支持嵌套对象、数组,是 VB6 中处理 JSON 数据的首选方案。
核心特性
- 双向转换: 支持 JSON 字符串解析和对象编码
- 嵌套支持: 无限层级的嵌套对象和数组
- 类型安全: 自动处理数据类型转换
- 格式化输出: 支持缩进美化输出
- 链式构建: 流畅的 JSON 构建 API
属性
| 属性 | 类型 | 说明 |
|---|---|---|
Root | cJson | 根节点对象 |
Item(key) | Variant | 访问指定键的值(默认成员) |
方法
Encode
将对象编码为 JSON 字符串
vb
Public Function Encode(Optional obj As Object, Optional Indent As Integer = 0, Optional UseDoubleQuotes As Boolean = True) As String参数:
obj- 要编码的对象(默认使用 Root)Indent- 缩进空格数(0=不换行)UseDoubleQuotes- 使用双引号(默认 True)
示例:
vb
' 简单编码
Dim json As New cJson
json("name") = "张三"
json("age") = 25
Dim jsonStr As String
jsonStr = json.Encode()
' 结果: {"name":"张三","age":25}
' 格式化输出
Dim prettyJson As String
prettyJson = json.Encode(, 2, True)
' 结果:
' {
' "name": "张三",
' "age": 25
' }Decode
解析 JSON 字符串
vb
Public Function Decode(jsonString As String) As cJson示例:
vb
' 解析 JSON
Dim jsonStr As String
jsonStr = "{\"name\":\"张三\",\"age\":25}"
Dim json As cJson
Set json = VBMAN.Json.Decode(jsonStr)
Debug.Print json("name") ' 张三
Debug.Print json("age") ' 25Item
访问或设置值
vb
' 读取
Dim value As Variant
value = json("key")
' 写入
json("key") = "value"
json("number") = 123
json("bool") = TrueNewItem / NewItems
创建嵌套对象/数组
vb
Public Function NewItem() As cJson
Public Function NewItems(key As String) As cJson示例:
vb
' 创建嵌套对象
Dim user As New cJson
user("id") = 1
user("name") = "张三"
With user.NewItem("address")
.Item("city") = "北京"
.Item("zip") = "100000"
End With
' 创建数组
Dim users As New cJson
With users.NewItems("data")
With .NewItem()
.Item("name") = "张三"
.Item("age") = 25
End With
With .NewItem()
.Item("name") = "李四"
.Item("age") = 30
End With
End With
Debug.Print users.Encode(, 2)
' 结果:
' {
' "data": [
' {"name":"张三","age":25},
' {"name":"李四","age":30}
' ]
' }Exists
检查键是否存在
vb
Public Function Exists(key As String) As Boolean示例:
vb
If json.Exists("email") Then
Debug.Print json("email")
Else
Debug.Print "email 不存在"
End IfRemove
删除键
vb
Public Sub Remove(key As String)综合示例
示例1: 构建复杂 JSON
vb
Private Sub BuildComplexJson()
Dim root As New cJson
' 基本信息
root("status") = "success"
root("message") = "操作成功"
root("timestamp") = Format(Now, "yyyy-MM-ddThh:mm:ss")
' 用户数据数组
With root.NewItems("users")
' 第一个用户
With .NewItem()
.Item("id") = 1
.Item("name") = "张三"
.Item("email") = "zhangsan@example.com"
' 嵌套地址
With .NewItem("address")
.Item("province") = "北京"
.Item("city") = "北京市"
.Item("detail") = "朝阳区xxx街道"
End With
' 嵌套订单数组
With .NewItems("orders")
With .NewItem()
.Item("order_id") = "ORD001"
.Item("amount") = 199.99
End With
With .NewItem()
.Item("order_id") = "ORD002"
.Item("amount") = 299.99
End With
End With
End With
' 第二个用户
With .NewItem()
.Item("id") = 2
.Item("name") = "李四"
.Item("email") = "lisi@example.com"
End With
End With
' 分页信息
With root.NewItem("pagination")
.Item("page") = 1
.Item("page_size") = 20
.Item("total") = 100
End With
' 输出 JSON
Dim jsonStr As String
jsonStr = root.Encode(, 2, True)
Debug.Print jsonStr
End Sub示例2: 解析 API 响应
vb
Private Sub ParseApiResponse(response As String)
Dim json As cJson
Set json = VBMAN.Json.Decode(response)
' 检查状态
If json("status") = "success" Then
' 获取用户数组
Dim users As cJson
Set users = json("data")("users")
' 遍历用户
Dim i As Integer
For i = 0 To users.Count - 1
Dim user As cJson
Set user = users(i)
Debug.Print "ID: " & user("id")
Debug.Print "Name: " & user("name")
Debug.Print "Email: " & user("email")
' 检查是否有地址
If user.Exists("address") Then
Debug.Print "City: " & user("address")("city")
End If
Debug.Print "---"
Next i
' 获取分页信息
Debug.Print "Total: " & json("data")("pagination")("total")
Else
Debug.Print "Error: " & json("message")
End If
End Sub示例3: 在实际项目中使用(来自 demos)
vb
' 构建 JSON 响应
Public Sub Json(ctx As cHttpServerContext)
Dim ID As Long: ID = ctx.Request.QueryString("id")
With New cJson
.Item("id") = ID
.Item("face") = ChrW(&H263A)
.Item("timestamp") = Now
.Item("status") = "success"
ctx.Response.Json .Root
End With
End Sub
' 解析请求数据
Public Sub HandleRequest(ctx As cHttpServerContext)
Dim requestData As String
requestData = ctx.Request.Body
Dim json As cJson
Set json = VBMAN.Json.Decode(requestData)
Dim username As String
Dim password As String
username = json("username")
password = json("password")
' 处理登录...
End Sub示例4: 数据库记录转 JSON
vb
Private Sub RecordsetToJson(rs As ADODB.Recordset)
Dim root As New cJson
' 添加元数据
root("count") = rs.RecordCount
root("timestamp") = Now
' 添加数据数组
With root.NewItems("data")
Do While Not rs.EOF
With .NewItem()
Dim i As Integer
For i = 0 To rs.Fields.Count - 1
.Item(rs.Fields(i).Name) = rs.Fields(i).Value
Next i
End With
rs.MoveNext
Loop
End With
' 输出
Debug.Print root.Encode(, 2)
End Sub示例5: INI 配置转 JSON
vb
Private Sub IniToJson()
VBMAN.Ini.LoadFrom App.Path & "\\config.ini"
Dim json As New cJson
' 转换所有 Section
Dim sectionKey As Variant
For Each sectionKey In VBMAN.Ini.Root.Keys
With json.NewItem(CStr(sectionKey))
Dim key As Variant
For Each key In VBMAN.Ini.Root(sectionKey).Keys
.Item(key) = VBMAN.Ini.Root(sectionKey)(key)
Next key
End With
Next sectionKey
' 保存为 JSON 文件
VBMAN.FileEx.SetBufferText(json.Encode(, 2), "UTF-8").SaveData App.Path & "\\config.json"
End Sub最佳实践
- 使用参数: 构建 JSON 时尽量使用 NewItem/NewItems
- 检查存在性: 读取前使用 Exists 检查键是否存在
- 错误处理: 解析 JSON 时添加错误处理
- 类型注意: VB6 是弱类型,注意数值和字符串的区别
- 格式化输出: 调试时使用缩进格式化便于阅读