Json阅读小工具制作

由于任务需要,需要对仅仅三个字段的Json文件进行阅读。这里制作了一个简易版的Json阅读工具,通过字段的遍历获取一个小工具,用来实现Json的可视化阅读

直接上代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Windows.Forms;

namespace JsonFormsTool
{
    public partial class Form1 : Form
    {
        private JsonNode currentJson;
        private List<TreeNode> searchResults = new List<TreeNode>();
        private int currentSearchIndex = -1;

        public Form1()
        {
            InitializeComponent();
            InitializeEventHandlers();
            this.Text = "Json查看工具";
        }

        private void InitializeEventHandlers()
        {
            // 打开文件按钮事件
            toolStripButton1.Click += ToolStripButton1_Click;

            // 搜索按钮事件
            toolStripButton2.Click += ToolStripButton2_Click;

            // 上一个搜索结果按钮事件
            toolStripButton3.Click += ToolStripButton3_Click;

            // 下一个搜索结果按钮事件
            toolStripButton4.Click += ToolStripButton4_Click;

            // 树形视图节点点击事件
            treeView1.AfterSelect += TreeView1_AfterSelect;

            // 搜索框按键事件
            toolStripTextBox1.KeyDown += ToolStripTextBox1_KeyDown;
        }

        private void ToolStripButton1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Json文件 (*.json)|*.json|所有文件 (*.*)|*.*";
                openFileDialog.Title = "打开Json文件";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        string filePath = openFileDialog.FileName;
                        string jsonContent = File.ReadAllText(filePath);

                        // 在RichTextBox中显示全文
                        richTextBox1.Text = jsonContent;

                        // 解析并显示到TreeView
                        ParseAndDisplayJson(jsonContent);

                        // 展开所有节点
                        treeView1.ExpandAll();

                        // 清空搜索结果
                        searchResults.Clear();
                        currentSearchIndex = -1;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"打开文件时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void ParseAndDisplayJson(string jsonContent)
        {
            try
            {
                // 解析JSON
                currentJson = JsonNode.Parse(jsonContent);
                if (currentJson == null)
                {
                    MessageBox.Show("无法解析JSON内容", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 清空TreeView
                treeView1.Nodes.Clear();

                // 创建根节点
                TreeNode rootNode;
                if (currentJson is JsonObject)
                {
                    rootNode = new TreeNode("根对象");
                    rootNode.Tag = currentJson;
                    treeView1.Nodes.Add(rootNode);
                    AddJsonObjectToTree((JsonObject)currentJson, rootNode);
                }
                else if (currentJson is JsonArray)
                {
                    rootNode = new TreeNode("根数组");
                    rootNode.Tag = currentJson;
                    treeView1.Nodes.Add(rootNode);
                    AddJsonArrayToTree((JsonArray)currentJson, rootNode);
                }
                else
                {
                    rootNode = new TreeNode($"值: {currentJson.ToString()}");
                    rootNode.Tag = currentJson;
                    treeView1.Nodes.Add(rootNode);
                }

                // 默认选择第一个节点
                if (treeView1.Nodes.Count > 0)
                {
                    treeView1.SelectedNode = treeView1.Nodes[0];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"解析JSON时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AddJsonObjectToTree(JsonObject jsonObject, TreeNode parentNode)
        {
            foreach (var property in jsonObject)
            {
                TreeNode node = new TreeNode(property.Key);
                node.Tag = property.Value;

                if (property.Value is JsonObject)
                {
                    node.Text += " : 对象";
                    AddJsonObjectToTree((JsonObject)property.Value, node);
                }
                else if (property.Value is JsonArray)
                {
                    node.Text += $" : 数组[{((JsonArray)property.Value).Count}]";
                    AddJsonArrayToTree((JsonArray)property.Value, node);
                }
                else
                {
                    string value = property.Value?.ToString() ?? "null";
                    if (value.Length > 50)
                        value = value.Substring(0, 50) + "...";
                    node.Text += $" : {value}";
                }

                parentNode.Nodes.Add(node);
            }
        }

        private void AddJsonArrayToTree(JsonArray jsonArray, TreeNode parentNode)
        {
            for (int i = 0; i < jsonArray.Count; i++)
            {
                TreeNode node = new TreeNode($"[{i}]");
                node.Tag = jsonArray[i];

                if (jsonArray[i] is JsonObject)
                {
                    node.Text += " : 对象";
                    AddJsonObjectToTree((JsonObject)jsonArray[i], node);
                }
                else if (jsonArray[i] is JsonArray)
                {
                    node.Text += $" : 数组[{((JsonArray)jsonArray[i]).Count}]";
                    AddJsonArrayToTree((JsonArray)jsonArray[i], node);
                }
                else
                {
                    string value = jsonArray[i]?.ToString() ?? "null";
                    if (value.Length > 50)
                        value = value.Substring(0, 50) + "...";
                    node.Text += $" : {value}";
                }

                parentNode.Nodes.Add(node);
            }
        }

        private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag is JsonNode jsonNode)
            {
                // 格式化JSON节点内容并显示
                string jsonString = jsonNode.ToJsonString(new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

                // 处理换行符
                jsonString = jsonString.Replace("\\n", "\n");

                richTextBox1.Text = jsonString;
            }
        }

        private void SearchJsonTree(string searchText)
        {
            if (string.IsNullOrWhiteSpace(searchText))
                return;

            searchResults.Clear();
            currentSearchIndex = -1;

            // 递归搜索所有节点
            SearchNodes(treeView1.Nodes, searchText);

            if (searchResults.Count > 0)
            {
                currentSearchIndex = 0;
                treeView1.SelectedNode = searchResults[0];
                treeView1.SelectedNode.BackColor = Color.Yellow;
                treeView1.SelectedNode.EnsureVisible();
            }
            else
            {
                MessageBox.Show("未找到匹配项", "搜索", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void SearchNodes(TreeNodeCollection nodes, string searchText)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    searchResults.Add(node);
                }

                SearchNodes(node.Nodes, searchText);
            }
        }

        private void HighlightSearchResult()
        {
            // 清除之前的高亮
            foreach (TreeNode node in searchResults)
            {
                node.BackColor = treeView1.BackColor;
            }

            // 高亮当前结果
            if (currentSearchIndex >= 0 && currentSearchIndex < searchResults.Count)
            {
                treeView1.SelectedNode = searchResults[currentSearchIndex];
                searchResults[currentSearchIndex].BackColor = Color.Yellow;
                searchResults[currentSearchIndex].EnsureVisible();
            }
        }

        private void ToolStripButton2_Click(object sender, EventArgs e)
        {
            SearchJsonTree(toolStripTextBox1.Text);
        }

        private void ToolStripButton3_Click(object sender, EventArgs e)
        {
            if (searchResults.Count > 0)
            {
                currentSearchIndex = (currentSearchIndex - 1 + searchResults.Count) % searchResults.Count;
                HighlightSearchResult();
            }
        }

        private void ToolStripButton4_Click(object sender, EventArgs e)
        {
            if (searchResults.Count > 0)
            {
                currentSearchIndex = (currentSearchIndex + 1) % searchResults.Count;
                HighlightSearchResult();
            }
        }

        private void ToolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SearchJsonTree(toolStripTextBox1.Text);
                e.Handled = true;
                e.SuppressKeyPress = true;
            }
        }
    }
}

显示效果:

这里支持搜索

另外附上可直接运行版本:
https://wwus.lanzouu.com/iJ0Xt2yms9kb
密码:9664

posted @ 2025-06-12 14:57  嘻嘻哈哈555  阅读(44)  评论(0)    收藏  举报