VB中使用JSON的实用指南
在Visual Basic(VB)开发中,JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,常用于前后端数据交互、配置文件读取等场景,VB本身并未内置JSON解析和生成功能,需借助第三方库或手动实现,本文将详细介绍如何在VB中使用JSON,包括环境准备、JSON解析与生成、常见问题解决及实用技巧。
环境准备:选择合适的JSON库
VB中使用JSON的核心是借助第三方库,以下是几种主流方案,可根据需求选择:
Newtonsoft.Json(推荐)
.NET生态中最流行的JSON库,功能强大、文档完善,支持.NET Framework、.NET Core/.NET 5+及VB项目。
安装方法:
- 通过NuGet包管理器:在VB项目中右键“管理NuGet程序包”→ 搜索“Newtonsoft.Json”→ 安装最新版本。
- 或通过.NET CLI:
Install-Package Newtonsoft.Json。
System.Text.Json(.NET Core/.NET 5+内置)
.NET Core及后续版本内置的JSON库,性能较好,无需额外安装,但API相对简洁,适合简单场景。
适用场景:仅限.NET Core/.NET 5+项目,VB.NET Core可直接使用。
VB6/VB.NET早期版本兼容方案
若使用VB6或旧版VB.NET,可考虑:
- Microsoft Script Control:通过调用JavaScript引擎解析JSON(需安装IE相关组件)。
- 第三方轻量级库:如VBJSON(开源,仅支持JSON解析,无生成功能)。
本文以Newtonsoft.Json为例,因其兼容性强、功能全面,适合大多数VB项目。
JSON解析:将JSON字符串转换为VB对象
JSON解析是指将JSON格式的字符串转换为VB可操作的对象(如字典、集合或自定义类),以下是具体步骤:
解析为JObject(动态对象)
JObject是Newtonsoft.Json提供的动态类型,可直接通过键访问JSON数据,无需预先定义类。
示例:假设有以下JSON字符串:
"{""name"":""张三"",""age"":25,""hobbies"":[""阅读"",""编程""],""address"":{""city"":""北京"",""district"":""朝阳区""}}"
VB代码:
Imports Newtonsoft.Json.Linq ' 导入Newtonsoft.Json命名空间
Module Module1
Sub Main()
Dim jsonStr As String = "{""name"":""张三"",""age"":25,""hobbies"":[""阅读"",""编程""],""address"":{""city"":""北京"",""district"":""朝阳区""}}"
' 解析为JObject
Dim jObj As JObject = JObject.Parse(jsonStr)
' 访问简单字段
Console.WriteLine("姓名:" & jObj("name").ToString()) ' 输出:姓名:张三
Console.WriteLine("年龄:" & jObj("age").ToString()) ' 输出:年龄:25
' 访问数组(JArray)
Dim hobbies As JArray = jObj("hobbies")
Console.WriteLine("爱好:")
For Each hobby As JValue In hobbies
Console.WriteLine("- " & hobby.ToString()) ' 输出:阅读、编程
Next
' 访问嵌套对象
Dim address As JObject = jObj("address")
Console.WriteLine("地址:" & address("city").ToString() & "-" & address("district").ToString()) ' 输出:地址:北京-朝阳区
Console.ReadKey()
End Sub
End Module
解析为自定义类(强类型)
若JSON结构固定,可通过定义VB类实现强类型解析,提升代码可读性和安全性。
步骤:
- 根据JSON结构定义VB类(属性名需与JSON键名一致,支持
<JsonProperty("")>特性指定映射)。 - 使用
JsonConvert.DeserializeObject(Of T)方法解析。
示例:
Imports Newtonsoft.Json ' 导入Newtonsoft.Json命名空间
' 定义自定义类
Public Class Person
<JsonProperty("name")> ' 特性:指定JSON键名映射到VB属性
Public Property Name As String
<JsonProperty("age")>
Public Property Age As Integer
<JsonProperty("hobbies")>
Public Property Hobbies As List(Of String)
<JsonProperty("address")>
Public Property Address As Address
End Class
Public Class Address
<JsonProperty("city")>
Public Property City As String
<JsonProperty("district")>
Public Property District As String
End Module
Module Module1
Sub Main()
Dim jsonStr As String = "{""name"":""张三"",""age"":25,""hobbies"":[""阅读"",""编程""],""address"":{""city"":""北京"",""district"":""朝阳区""}}"
' 解析为自定义类
Dim person As Person = JsonConvert.DeserializeObject(Of Person)(jsonStr)
' 强类型访问
Console.WriteLine("姓名:" & person.Name) ' 输出:姓名:张三
Console.WriteLine("年龄:" & person.Age) ' 输出:年龄:25
Console.WriteLine("第一个爱好:" & person.Hobbies(0)) ' 输出:第一个爱好:阅读
Console.WriteLine("地址:" & person.Address.City & "-" & person.Address.District) ' 输出:地址:北京-朝阳区
Console.ReadKey()
End Sub
End Module
处理复杂JSON(数组、动态键等)
若JSON是数组(如[{...}, {...}]),可解析为List(Of T)或JArray:
示例(JSON数组解析):
Dim jsonArrayStr As String = "[{""name"":""张三"",""age"":25},{""name"":""李四"",""age"":30}]"
Dim jArray As JArray = JArray.Parse(jsonArrayStr)
For Each item As JObject In jArray
Console.WriteLine("姓名:" & item("name") & ",年龄:" & item("age"))
Next
' 或解析为自定义类列表
Dim people As List(Of Person) = JsonConvert.DeserializeObject(Of List(Of Person))(jsonArrayStr)
For Each p As Person In people
Console.WriteLine(p.Name & " - " & p.Age)
Next
JSON生成:将VB对象转换为JSON字符串
与解析相反,JSON生成是将VB对象(如类、字典、集合)转换为JSON字符串,常用于数据返回或配置保存。
生成JSON字符串(Newtonsoft.Json)
使用JsonConvert.SerializeObject方法,支持格式化输出。
示例(自定义类转JSON):
Imports Newtonsoft.Json
Module Module1
Sub Main()
' 创建自定义对象
Dim person As New Person With {
.Name = "王五",
.Age = 28,
.Hobbies = New List(Of String) From {"旅行", "摄影"},
.Address = New Address With {
.City = "上海",
.District = "浦东新区"
}
}
' 转换为JSON字符串(默认不格式化)
Dim jsonStr As String = JsonConvert.SerializeObject(person)
Console.WriteLine("未格式化JSON:" & jsonStr)
' 输出:未格式化JSON:{"name":"王五","age":28,"hobbies":["旅行","摄影"],"address":{"city":"上海","district":"浦东新区"}}
' 转换为格式化JSON(缩进2空格)
Dim formattedJson As String = JsonConvert.SerializeObject(person, Formatting.Indented)
Console.WriteLine("格式化JSON:" & vbCrLf & formattedJson)
' 输出:
' 格式化JSON:
' {
' "name": "王五",
' "age": 28,
' "hobbies": [
' "旅行",
' "摄影"
' ],
' "address": {
' "city": "上海",
' "district": "浦东新区"
' }
' }
Console.ReadKey()
End Sub
End Module
生成复杂JSON(嵌套对象、数组)
嵌套对象或数组会自动处理,只需确保VB对象结构正确即可。
' 创建包含数组的对象
Dim employees As New List(Of Person) From {
New Person With {.Name = "赵六", .Age = 35},
New Person With {.Name = "钱七", .Age = 40}
}
Dim company As New With {
.CompanyName = "某科技公司",
.Employees = employees
}
Dim companyJson As String = JsonConvert.SerializeObject(company, Formatting.Indented)
Console.WriteLine(companyJson)
' 输出:
' {
' "CompanyName": "某科技公司",
' "Employees": [
' {
' "name": "赵六",
' "age":


还没有评论,来说两句吧...