Json閱讀小工具制作
由于任務(wù)需要,需要對僅僅三個字段的Json文件進(jìn)行閱讀。這里制作了一個簡易版的Json閱讀工具,通過字段的遍歷獲取一個小工具,用來實現(xiàn)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;
// 上一個搜索結(jié)果按鈕事件
toolStripButton3.Click += ToolStripButton3_Click;
// 下一個搜索結(jié)果按鈕事件
toolStripButton4.Click += ToolStripButton4_Click;
// 樹形視圖節(jié)點點擊事件
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);
// 展開所有節(jié)點
treeView1.ExpandAll();
// 清空搜索結(jié)果
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內(nèi)容", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// 清空TreeView
treeView1.Nodes.Clear();
// 創(chuàng)建根節(jié)點
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("根數(shù)組");
rootNode.Tag = currentJson;
treeView1.Nodes.Add(rootNode);
AddJsonArrayToTree((JsonArray)currentJson, rootNode);
}
else
{
rootNode = new TreeNode($"值: {currentJson.ToString()}");
rootNode.Tag = currentJson;
treeView1.Nodes.Add(rootNode);
}
// 默認(rèn)選擇第一個節(jié)點
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 += $" : 數(shù)組[{((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 += $" : 數(shù)組[{((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節(jié)點內(nèi)容并顯示
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;
// 遞歸搜索所有節(jié)點
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;
}
// 高亮當(dāng)前結(jié)果
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

浙公網(wǎng)安備 33010602011771號