如何在C#中的Winform tabPage上显示反序列化的Json结果

问题描述

在这里我需要你的帮助,我无法编写逻辑来在 Winforms C# 中的 tabPage 上显示反序列化的 JSON 结果

    public Form1()
    {
       

        var path = @"C:\Users\elitebook\source\repos\ExamCBT\question.json";

        string jsonFile = File.ReadAllText(path);

        Question q = JsonConvert.DeserializeObject<Question>(jsonFile);

          InitializeComponent();
       
    }

 jsonFile = tabPage2.ToString();

解决方法

您可以使用这些方法对 JSON 进行序列化和反序列化。只需下载 Newtonsoft.Json NuGet 包。

static class FileHelper
{
    public static void JsonSerialize(object obj,string fileName)
    {
        using (var sw = new System.IO.StreamWriter($"{fileName}.json"))
            using (var jw = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                var serializer = new Newtonsoft.Json.JsonSerializer();
                jw.Formatting = Newtonsoft.Json.Formatting.Indented;
                serializer.Serialize(jw,obj);
            }
    }
    public static void JsonDeserialize(out string/*object,List<>,or something else*/ obj,string fileName)
    {
        using (var sr = new System.IO.StreamReader($"{fileName}.json"))
        {
            using (var jr = new Newtonsoft.Json.JsonTextReader(sr))
            {
                var serializer = new Newtonsoft.Json.JsonSerializer();
                try
                {
                    obj = serializer.Deserialize<string /*object,or something else...*/>(jr);
                }
                catch
                {
                    obj = null;
                }
            }
        }
    }
}

您可以像这样将 JSON 数据添加到 TabPage

Label label = new Label(); // label can be textbox,button or something else...
FileHelper.JsonDeserialize(out string /*object,or something else...*/ data,"test");
label.Text = data //data type is string
tabPage1.Controls.Add(label);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...