使用C#或VB遍历大型嵌套JSON字符串并转换为DataTable
Hey there! I’ve been in your shoes before—nested JSON traversal feels tricky at first, but once you map out the parent-child relationships clearly, it’s totally straightforward. Let’s walk through how to fix this with your MenuObject class and Newtonsoft.Json (Json.NET):
Step 1: Fix Serialization Mapping (Critical!)
First, make sure your MenuObject class aligns perfectly with your JSON structure. If your JSON uses hyphens (like data-tagname) instead of underscores, add JsonProperty attributes to bridge the gap—this is a super common pitfall that breaks deserialization:
Imports Newtonsoft.Json Public Class MenuObject <JsonProperty("data-tagname")> Public Property data_tagname As String <JsonProperty("data-title")> Public Property data_title As String <JsonProperty("data-menuid")> Public Property data_menuid As String <JsonProperty("data-parentid")> Public Property data_parentid As String <JsonProperty("data-cmsid")> Public Property data_cmsid As String ' Add any other missing properties here End Class
Step 2: Deserialize JSON to MenuObject List
Convert your raw JSON string into a list of MenuObject instances first:
Dim jsonString As String = "Your large nested JSON string here" Dim allMenuItems As List(Of MenuObject) = JsonConvert.DeserializeObject(Of List(Of MenuObject))(jsonString)
Step 3: Build a Parent-Child Lookup Dictionary
To avoid wasting time searching for child items repeatedly, create a dictionary that maps parent IDs to their corresponding child menus:
' Group menu items by their parent ID for fast lookup Dim parentChildMap As Dictionary(Of String, List(Of MenuObject)) = allMenuItems.GroupBy(Function(item) item.data_parentid) .ToDictionary(Function(g) g.Key, Function(g) g.ToList())
Step 4: Recursively Traverse the Nested Structure
Use a recursive method to walk through the hierarchy, starting from your root level (adjust the root parent ID to match your data—common values are empty string, "0", or "null"):
' Start traversal from root items (update rootParentId to fit your JSON) Dim rootParentId As String = "" TraverseMenu(parentChildMap, rootParentId, 0) ' Recursive traversal method with hierarchy indentation Private Sub TraverseMenu(parentChildMap As Dictionary(Of String, List(Of MenuObject)), parentId As String, currentLevel As Integer) If parentChildMap.ContainsKey(parentId) Then For Each menuItem As MenuObject In parentChildMap(parentId) ' Process the item here (example: print with hierarchy indent) Console.WriteLine($"{New String("-"c, currentLevel * 2)} {menuItem.data_title} (Menu ID: {menuItem.data_menuid})") ' Recurse into this item's children TraverseMenu(parentChildMap, menuItem.data_menuid, currentLevel + 1) Next End If End Sub
Alternative: Traverse Raw JSON Without Full Serialization
If you don’t need to map everything to MenuObject first, you can use Newtonsoft’s JToken to traverse the raw JSON structure directly:
Dim jsonToken As JToken = JToken.Parse(jsonString) TraverseJToken(jsonToken, 0) Private Sub TraverseJToken(token As JToken, currentLevel As Integer) Select Case token.Type Case JTokenType.Object For Each prop As JProperty In token.Children(Of JProperty)() Console.WriteLine($"{New String("-"c, currentLevel * 2)} {prop.Name}: {prop.Value}") TraverseJToken(prop.Value, currentLevel + 1) Next Case JTokenType.Array For Each item As JToken In token.Children() TraverseJToken(item, currentLevel + 1) Next Case Else Console.WriteLine($"{New String("-"c, currentLevel * 2)} {token.ToString()}") End Select End Sub
Quick Troubleshooting Tips
- Null Properties After Deserialization: Double-check your
JsonPropertyattributes—mismatched names are the #1 cause here. - No Root Items Showing: Verify your
rootParentIdmatches the parent ID used for top-level menus in your JSON. - Infinite Recursion: If your JSON has circular links, add a tracking list to skip already visited menu IDs.
内容的提问来源于stack exchange,提问作者WNM Derek

