How to display deserialized Json result on Winform tabPage in C#

472 Views Asked by At

Please I need your help here, I could not write the logic to display the deserialized JSON result on tabPage in Winforms C#

    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();
1

There are 1 best solutions below

2
turaltahmazli On

You can use these methods for serializing & deserializing JSON. Just download the Newtonsoft.Json NuGet package.

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, List<>, or something else...*/>(jr);
                }
                catch
                {
                    obj = null;
                }
            }
        }
    }
}

And you can add JSON data to TabPage like this.

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