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

VB.NET使用Newtonsoft JSON如何获取嵌套JSON内指定键对应的值

VB.NET 基于Newtonsoft.Json按指定identity type获取对应status值的实现

原有代码问题梳理

  • 未将反序列化结果显式转换为JObject类型,直接通过索引取值容易出现类型异常
  • 循环边界设置错误:数组索引从0开始,遍历上限应该为元素总数减1,否则会触发索引越界错误
  • 缺少匹配指定identity type的逻辑,无法筛选到目标status值

正确实现代码

首先需要引入对应的命名空间:
Imports Newtonsoft.Json.Linq

完整实现逻辑如下,假设你要匹配的目标identity type存放在targetType变量中:

Dim jsonResult As String = myReader.ReadToEnd()
' 解析JSON为JObject类型方便后续节点操作
Dim jsonObject As JObject = JObject.Parse(jsonResult)
' 获取identity_status节点对应的数组
Dim identityStatusArr As JArray = jsonObject("owner")("identity_statuses")("identity_status")

Dim targetType As String = "你需要查询的identity type具体值"
Dim targetStatus As String = String.Empty

' 遍历数组匹配目标类型
For Each item As JObject In identityStatusArr
    If item("identity_type").ToString() = targetType Then
        targetStatus = item("identity_status").ToString()
        Exit For ' 匹配到结果后直接退出循环减少性能消耗
    End If
Next
' 此时targetStatus即为对应identity type的status值

优化建议

  • 可以提前定义和JSON结构匹配的强类型实体类,使用JsonConvert.DeserializeObject(Of 自定义实体类)(jsonResult)进行反序列化,编译阶段即可排查字段不存在、类型不匹配等问题,稳定性更高
  • 取值时可以添加空值判断逻辑,比如判断jsonObject("owner")?("identity_statuses")?("identity_status")是否为Nothing,避免JSON结构异常时触发空引用错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:36:07