VB.NET 如何递归遍历结构不确定的嵌套动态JSON获取全量键值对
VB.NET 不规则动态JSON全层级递归解析实现
原有方案的实际问题
- 最初使用
JavaScriptSerializer将JSON反序列化为通用对象后直接遍历:仅能获取顶层键值,嵌套子键会直接被输出为Dictionary类型标识,无法读取子级实际值 - 改用
Newtonsoft.Json基于JProperty做单层遍历:仅能提取非嵌套的顶层信息,无法自动深入嵌套结构完成全量解析
核心实现能力要求
- 无需提前校验特定键是否存在
- 支持自动递归穿透全层级嵌套结构
- 完整提取所有层级的键与对应值
- 兼容包含数组、多层嵌套对象的各类不规则JSON结构
具体实现代码
基于Newtonsoft.Json的JToken分层体系实现递归遍历,无需提前定义任何强类型类:
Imports Newtonsoft.Json.Linq Public Module DynamicJsonParser ''' <summary> ''' 扁平化解析动态JSON,输出全层级路径-值映射 ''' </summary> ''' <param name="rawJson">待解析的原始JSON字符串</param> ''' <param name="basePath">初始遍历路径标记</param> ''' <returns>所有层级的键值映射集合</returns> Public Function ParseAllLevels(rawJson As String, Optional basePath As String = "") As Dictionary(Of String, Object) Dim resultMap = New Dictionary(Of String, Object)() Dim rootToken = JToken.Parse(rawJson) RecursiveTraverse(rootToken, basePath, resultMap) Return resultMap End Function Private Sub RecursiveTraverse(token As JToken, currentPath As String, targetMap As Dictionary(Of String, Object)) Select Case token.Type Case JTokenType.Object ' 递归遍历嵌套对象的所有属性 For Each prop In token.Children(Of JProperty)() Dim fullPath = If(String.IsNullOrEmpty(currentPath), prop.Name, $"{currentPath}.{prop.Name}") RecursiveTraverse(prop.Value, fullPath, targetMap) Next Case JTokenType.Array ' 递归遍历数组元素,用索引标记数组位置 Dim arrayIndex = 0 For Each item In token.Children() Dim fullPath = If(String.IsNullOrEmpty(currentPath), arrayIndex.ToString(), $"{currentPath}[{arrayIndex}]") RecursiveTraverse(item, fullPath, targetMap) arrayIndex += 1 Next Case Else ' 基础值类型直接存入结果集 Dim finalKey = If(String.IsNullOrEmpty(currentPath), token.Path, currentPath) targetMap.Add(finalKey, token.ToObject(Of Object)()) End Select End Sub End Module
调用示例
' 测试传入结构不规则的JSON Dim testJson = "{""user"":{""nickname"":""李四"",""skill"":[""VB.NET"",""JSON解析""]},""online"":true}" Dim parsedResult = ParseAllLevels(testJson) ' 最终提取的全量键值包含: ' user.nickname -> 李四 ' user.skill[0] -> VB.NET ' user.skill[1] -> JSON解析 ' online -> True
方案适配特性
- 不需要提前预判JSON包含的键,部分键随机存在的场景不会触发空引用异常
- 递归逻辑自动识别嵌套对象、数组结构,会一直穿透到最底层的基础值,不会停留在某一层输出类型标识
- 对键集合差异大、层级数量不固定的JSON实例,可直接复用同一解析逻辑,不需要调整代码
内容的提问来源于stack exchange,提问作者Tiago
相关产品推荐
相关产品推荐

