问题描述
请在这里我需要你的帮助,我无法编写逻辑来在 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);