简体   繁体   中英

Deserialization problem while loading objects

My aim is to set the bool values where they left of by reading from txt.

Here is my problem, simply, and step by step;

  1. I set the values to "true" by clicking the set button

  2. In txt file, JSON objects are set to true successfully

  3. I closed and re-run the program

  4. I expect the current bool flags to be "true" from previous run

However they are still false , I there is a problem with " deserialize " Button2_Click_1 is just showing me the current values of the flags. Another point is that in the txt file flags are still true which seems okay.

I changed the order of deserialize and serialize yet nothing changed.

   [Serializable]
    class Class1
    {
        public bool flag { get; set; }
        public bool flag2 { get; set; }
        public Class1()
        {
            flag = false;
            flag2 = false;
        }
    }

[Serializable]
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        Class1 c1 = new Class1();


        private void Button1_Click(object sender, EventArgs e)
        {
            c1.flag = true;
            c1.flag2 = true;

            //deserialize
            string json2 = File.ReadAllText("path.txt");
            Class1 f2 = JsonConvert.DeserializeObject<Class1>(json2);

            //serialize
            string json = JsonConvert.SerializeObject(c1);
            File.WriteAllText("path.txt", json);


            Console.WriteLine(json);


        }

        private void Button2_Click_1(object sender, EventArgs e)
        {
            Console.WriteLine("Current Status of Flag1: "+c1.flag);
            Console.WriteLine("Current Status of Flag2: " + c1.flag2);
        }

If you are clicking Button2 without first clicking Button1 when the application starts up, c1 will be false by default since the default value of a boolean is false. if you wish to load the json when you click Button2 please add the following code above Console.WriteLine:

c1 = JsonConvert.DeserializeObject<Class1>(File.ReadAllText("path.txt"));

so that it becomes

    private void Button2_Click_1(object sender, EventArgs e)
    {
        c1 = JsonConvert.DeserializeObject<Class1>(File.ReadAllText("path.txt"));
        Console.WriteLine("Current Status of Flag1: "+c1.flag);
        Console.WriteLine("Current Status of Flag2: " + c1.flag2);
    }

and this should fix your issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM