VB.NET读写JSON文件内容完全指南
在.NET开发中,JSON(JavaScript Object Notation)已成为数据交换的主流格式之一,本文将详细介绍如何使用VB.NET语言实现JSON文件的读写操作,涵盖从基础概念到实际应用的完整流程。
JSON与VB.NET简介
JSON是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,在VB.NET中,我们可以使用内置的System.Text.Json命名空间(.NET Core 3.0及以上版本)或第三方库如Newtonsoft.Json(Json.NET)来处理JSON数据。
使用System.Text.Json读写JSON(推荐)
1 基本设置
首先确保你的项目引用了System.Text.Json命名空间:
Imports System.Text.Json Imports System.Text.Json.Serialization Imports System.IO
2 定义JSON对应的VB.NET类
为了将JSON数据反序列化为VB.NET对象,我们需要创建与JSON结构匹配的类:
Public Class Person
<JsonPropertyName("name")>
Public Property Name As String
<JsonPropertyName("age")>
Public Property Age As Integer
<JsonPropertyName("isStudent")>
Public Property IsStudent As Boolean
<JsonPropertyName("address")>
Public Property Address As Address
End Class
Public Class Address
<JsonPropertyName("street")>
Public Property Street As String
<JsonPropertyName("city")>
Public Property City As String
End Class
3 将对象写入JSON文件(序列化)
Public Sub WriteJsonToFile(filePath As String, person As Person)
Dim options As New JsonSerializerOptions With {
.WriteIndented = True,
.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
}
Dim jsonString As String = JsonSerializer.Serialize(person, options)
File.WriteAllText(filePath, jsonString)
Console.WriteLine("JSON文件已成功写入: " & filePath)
End Sub
4 从JSON文件读取数据(反序列化)
Public Function ReadJsonFromFile(filePath As String) As Person
If Not File.Exists(filePath) Then
Throw New FileNotFoundException("指定的JSON文件不存在", filePath)
End If
Dim jsonString As String = File.ReadAllText(filePath)
Dim person As Person = JsonSerializer.Deserialize(Of Person)(jsonString)
Return person
End Function
5 使用示例
Sub Main()
Dim filePath As String = "person.json"
' 创建示例对象
Dim samplePerson As New Person With {
.Name = "张三",
.Age = 30,
.IsStudent = False,
.Address = New Address With {
.Street = "中山路123号",
.City = "北京"
}
}
' 写入JSON文件
WriteJsonToFile(filePath, samplePerson)
' 从JSON文件读取
Dim readPerson As Person = ReadJsonFromFile(filePath)
' 输出读取的数据
Console.WriteLine("姓名: " & readPerson.Name)
Console.WriteLine("年龄: " & readPerson.Age)
Console.WriteLine("是否学生: " & readPerson.IsStudent)
Console.WriteLine("地址: " & readPerson.Address.Street & ", " & readPerson.Address.City)
End Sub
使用Newtonsoft.Json读写JSON(传统方式)
如果你仍在使用旧版.NET Framework或更喜欢Newtonsoft.Json,以下是实现方式:
1 安装Newtonsoft.Json
通过NuGet包管理器安装Newtonsoft.Json包。
2 读写实现
Imports Newtonsoft.Json
Imports System.IO
Public Sub WriteJsonWithNewtonsoft(filePath As String, person As Person)
Dim jsonString As String = JsonConvert.SerializeObject(person, Formatting.Indented)
File.WriteAllText(filePath, jsonString)
End Sub
Public Function ReadJsonWithNewtonsoft(filePath As String) As Person
Dim jsonString As String = File.ReadAllText(filePath)
Return JsonConvert.DeserializeObject(Of Person)(jsonString)
End Function
处理复杂数据结构
1 处理数组/列表
Public Class PeopleList
<JsonPropertyName("people")>
Public Property People As List(Of Person)
End Class
' 写入JSON数组
Dim peopleList As New PeopleList With {
.People = New List(Of Person) From {
New Person With {.Name = "张三", .Age = 30},
New Person With {.Name = "李四", .Age = 25}
}
}
WriteJsonToFile("people.json", peopleList)
' 读取JSON数组
Dim readList As PeopleList = ReadJsonFromFile("people.json")
For Each p In readList.People
Console.WriteLine(p.Name & " - " & p.Age)
Next
2 处理动态JSON
对于不确定结构的JSON,可以使用JsonElement或JObject(Newtonsoft.Json):
' 使用System.Text.Json处理动态JSON
Dim dynamicJson As JsonElement = JsonSerializer.Deserialize(Of JsonElement)(jsonString)
Dim name As String = dynamicJson.GetProperty("name").GetString()
Dim age As Integer = dynamicJson.GetProperty("age").GetInt32()
' 使用Newtonsoft.Json的JObject
Dim jObject As JObject = JObject.Parse(jsonString)
Dim name As String = jObject("name").ToString()
错误处理与最佳实践
- 始终检查文件是否存在:在读取文件前验证文件路径的有效性
- 使用异常处理:捕获可能出现的
JsonException和IOException - 配置序列化选项:根据需要设置日期格式、null值处理等
- 考虑性能:对于大文件,考虑使用流式处理而非一次性读取整个文件
Public Function SafeReadJson(filePath As String) As Person
Try
If Not File.Exists(filePath) Then
Console.WriteLine("警告: 文件不存在,返回默认对象")
Return New Person() ' 返回默认对象或Nothing
End If
Dim jsonString As String = File.ReadAllText(filePath)
Return JsonSerializer.Deserialize(Of Person)(jsonString)
Catch ex As JsonException
Console.WriteLine("JSON解析错误: " & ex.Message)
Return Nothing
Catch ex As IOException
Console.WriteLine("文件操作错误: " & ex.Message)
Return Nothing
End Try
End Function
本文详细介绍了在VB.NET中读写JSON文件的多种方法,推荐使用.NET Core 3.0+内置的System.Text.Json,它性能更好且无需额外依赖,对于复杂场景,可以考虑使用Newtonsoft.Json提供的丰富功能,通过合理定义数据类、正确处理序列化选项以及完善的错误处理机制,你可以轻松地在VB.NET应用中实现JSON数据的持久化存储和读取。



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