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

VB.NET中state为success时如何获取JSON内height和width值

解决VB.NET中JSON反序列化后获取嵌套数据的问题

首先你的JSON字符串存在语法错误,"data"后面缺少冒号,修正后的JSON应该是:

{ 
    "state":"success",
    "data": {
        "height":200,
        "width":0 
    }
}

接下来需要定义与JSON结构对应的VB.NET类,这样反序列化后才能直接访问嵌套的height和width:

' 嵌套的数据类,对应JSON里的data对象
Public Class DataModel
    Public Property height As Integer
    Public Property width As Integer
End Class

' 顶层类,对应整个JSON结构,也就是你代码里的xyz
Public Class xyz
    Public Property state As String
    Public Property data As DataModel
End Class

完成反序列化后,你可以通过以下方式在state为success时获取嵌套属性:

Dim jsonObject = JsonConvert.DeserializeObject(Of xyz)(abc)

If jsonObject.state = "success" Then
    ' 获取height和width的值
    Dim heightValue = jsonObject.data.height
    Dim widthValue = jsonObject.data.width
    
    ' 这里可添加业务逻辑,比如使用这些值
    Console.WriteLine($"Height: {heightValue}, Width: {widthValue}")
End If

注意事项

  • 如果JSON属性名和VB.NET属性名大小写不一致(比如JSON用小写,VB.NET习惯用 PascalCase),可以用JsonProperty特性映射:
    Public Class xyz
        <JsonProperty("state")>
        Public Property State As String
        
        <JsonProperty("data")>
        Public Property Data As DataModel
    End Class
    
  • 确保已引用Newtonsoft.Json(Json.NET)库,因为你用到了JsonConvert.DeserializeObject方法。

内容的提问来源于stack exchange,提问作者Rushikesh Gawhale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:42:50