发布时间:2025-12-10 12:54:21 浏览次数:9
C#中的RichTextBox控件是Windows Form应用程序中非常常用的控件,它可以实现文本输入和显示的功能。而JSON是一种轻量级的数据交换格式,常被用于Web应用程序中,可以帮助程序更方便地传递数据。这篇文章将介绍如何在C#的RichTextBox控件中显示JSON格式的数据。
using System.IO;using System.Windows.Forms;using Newtonsoft.Json;namespace demo{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){//读取JSON格式的数据StreamReader sr = new StreamReader(Application.StartupPath + "\\data.json");string str = sr.ReadToEnd();sr.Close();//将JSON数据转换为对象object obj = JsonConvert.DeserializeObject(str);//在RichTextBox中显示JSON数据richTextBox1.Text = JsonConvert.SerializeObject(obj, Formatting.Indented);}}}上面的代码首先使用StreamReader读取本地的JSON数据,然后通过JsonConvert类将JSON数据转换为对象。最后使用JsonConvert类的SerializeObject方法将对象转换为JSON格式并显示在RichTextBox控件中。其中Formatting.Indented参数表示JSON数据使用缩进格式进行显示。