You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.Net中反序列化JSON?附RestClient请求代码示例

VB.Net中JSON数据反序列化实现方法

我通过RestSharp发起请求获取到了JSON格式的传感器历史数据,数据存储在Respons对象的Content属性中,但不知道如何将其反序列化为可直接使用的对象。以下是我的请求代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim client As New RestClient(BaseUrl)
    Dim Respons As Object

    client.Authenticator = OAuth1Authenticator.ForProtectedResource(PublicKey, PrivateKey, Token, TokenSecret)

    Dim request As New RestRequest("xml/devices/list", Method.Get)
    Respons = client.Execute(request)

    Console.WriteLine(Respons.Content)
    Console.ReadLine()

    Dim request2 As New RestRequest("json/sensor/history?id=1556402310&IncludeUnit=1&InculdeHumanReadableDate=1", Method.Get)
    Respons = client.Execute(request2)

    Console.WriteLine(Respons.Content)
    Console.ReadLine()
End Sub

解决方案步骤

1. 定义匹配JSON结构的实体类

根据你提供的JSON格式截图,创建对应的数据类:

Public Class SensorHistoryItem
    Public Property HumanReadableDate As String
    Public Property Value As Decimal ' 根据实际数据类型调整,如整数用Integer、字符串用String
    Public Property Unit As String
End Class

2. 选择反序列化工具实现转换

推荐两种VB.Net常用的反序列化方案:

方案一:使用Newtonsoft.Json(Json.NET)
  • 先通过NuGet包管理器安装Newtonsoft.Json
  • 修改请求后的代码,添加反序列化逻辑:
' 执行request2请求后
Respons = client.Execute(request2)

' 把JSON内容反序列化为实体集合
Dim sensorHistoryList As List(Of SensorHistoryItem) = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of SensorHistoryItem))(Respons.Content)

' 遍历输出数据示例
For Each item In sensorHistoryList
    Console.WriteLine($"日期:{item.HumanReadableDate},数值:{item.Value},单位:{item.Unit}")
Next
Console.ReadLine()
方案二:使用System.Text.Json(.NET Core/.NET 5+内置)
  • 无需额外安装包,直接使用内置类库:
' 执行request2请求后
Respons = client.Execute(request2)

' 配置序列化选项,启用大小写不敏感匹配
Dim options As New System.Text.Json.JsonSerializerOptions With {
    .PropertyNameCaseInsensitive = True
}

' 把JSON内容反序列化为实体集合
Dim sensorHistoryList As List(Of SensorHistoryItem) = System.Text.Json.JsonSerializer.Deserialize(Of List(Of SensorHistoryItem))(Respons.Content, options)

' 遍历输出数据示例
For Each item In sensorHistoryList
    Console.WriteLine($"日期:{item.HumanReadableDate},数值:{item.Value},单位:{item.Unit}")
Next
Console.ReadLine()

注意事项

  • 确保实体类的属性名称与JSON中的键一致,或启用大小写不敏感匹配规避名称大小写差异
  • 根据JSON中实际数据类型调整实体类属性的类型(比如Value如果是字符串则改为String)

内容的提问来源于stack exchange,提问作者Victor Wallenberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:30:59