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

如何在WPF TreeView中展示JSON?附实现代码片段

在WPF TreeView中展示JSON数据的完整实现

我来帮你把这段代码补全并优化,让它能顺利把JSON数据展示在WPF TreeView里。首先看你现有的代码,GetThreadedObject方法还没写完,这是反序列化JSON的关键步骤,咱们一步步来:

第一步:安装JSON序列化库

首先要安装Newtonsoft.Json(也叫Json.NET),这是WPF中处理JSON最常用的库。你可以通过NuGet包管理器搜索安装,或者在Package Manager Console里执行命令:

Install-Package Newtonsoft.Json

第二步:补全后台代码

下面是完整的MainWindow类代码,我帮你完善了反序列化逻辑,并且调整了数据绑定的处理方式:

Imports Newtonsoft.Json

Class MainWindow
    Public Sub New()
        InitializeComponent()
        ' 读取JSON文件内容
        Dim jsonContent = GetJSON()
        ' 反序列化为动态JSON对象
        Dim jsonObject = GetDeserializedObject(jsonContent)
        ' 获取"phases"数组的第一个元素作为数据源
        Dim phasesData = jsonObject("phases")(0)
        ' 将JSON结构转换为TreeView可绑定的层级数据
        tView.ItemsSource = ConvertToTreeItems(phasesData)
    End Sub

    Private Function GetJSON() As String
        ' 用Path.Combine构建路径,避免分隔符错误
        Dim jsonPath = System.IO.Path.Combine(My.Application.Info.DirectoryPath, "UAL525 Phase of Flight.json")
        Return System.IO.File.ReadAllText(jsonPath)
    End Function

    Private Function GetDeserializedObject(json As String) As Object
        ' 解析JSON为JObject动态对象
        Return Newtonsoft.Json.Linq.JObject.Parse(json)
    End Function

    ' 递归转换JSON结构为TreeView节点集合
    Private Function ConvertToTreeItems(item As Object) As List(Of TreeItem)
        Dim treeItems As New List(Of TreeItem)
        
        ' 处理JSON对象类型
        If TypeOf item Is Newtonsoft.Json.Linq.JObject Then
            For Each prop In DirectCast(item, Newtonsoft.Json.Linq.JObject).Properties()
                Dim treeItem As New TreeItem With {
                    .Name = prop.Name,
                    .Value = prop.Value.ToString()
                }
                ' 如果值是嵌套对象/数组,递归添加子节点
                If prop.Value.Type = Newtonsoft.Json.Linq.JTokenType.Object OrElse prop.Value.Type = Newtonsoft.Json.Linq.JTokenType.Array Then
                    treeItem.Children = ConvertToTreeItems(prop.Value)
                End If
                treeItems.Add(treeItem)
            Next
        ' 处理JSON数组类型
        ElseIf TypeOf item Is Newtonsoft.Json.Linq.JArray Then
            For Each element In DirectCast(item, Newtonsoft.Json.Linq.JArray)
                treeItems.AddRange(ConvertToTreeItems(element))
            Next
        End If
        
        Return treeItems
    End Function
End Class

' 用于TreeView绑定的实体类
Public Class TreeItem
    Public Property Name As String
    Public Property Value As String
    Public Property Children As List(Of TreeItem)
End Class

第三步:编写TreeView的XAML

TreeView需要用HierarchicalDataTemplate来递归展示嵌套的JSON结构,下面是对应的XAML示例:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"
        Title="JSON TreeView" Height="450" Width="800">
    <Grid>
        <TreeView x:Name="tView">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type local:TreeItem}" ItemsSource="{Binding Children}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}" FontWeight="Bold" Margin="0,0,5,0"/>
                        <TextBlock Text="{Binding Value}"/>
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>
</Window>

关键说明:

  • 我修正了原代码里的GetJASN笔误,改用Path.Combine构建文件路径,避免因系统分隔符差异导致的错误。
  • ConvertToTreeItems是核心逻辑,它会递归遍历JSON的所有嵌套结构,把数据转换为TreeItem实体类集合,让TreeView能自动展示层级关系。
  • 如果你的JSON结构是固定的,建议定义对应的强类型类替代动态对象,这样代码会更健壮,还能获得IDE智能提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:21:19