none
How to edit a JSON string and save it back to the file using a button? RRS feed

  • Question

  • I am creating a windows form application with C#.

    The application basically will take user input using 8 texboxes. The user data are saved to a structured JSON file, and at some point the user will need to change some data, for that reason, a click buttons were created (forward, backward, first and last) to go through the data, the data will be displayed on the textboxes and then the user can change some entries and save them back to the same string. but it doesn't seem the script is taking the new entries.

    This is how the JSON file looks like

    [
      {
        "Record": 1,
        "IPaddress": "192.168.6.1",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "\home\config",
        "destfolder": "C:\Users\Sami",
        "filextension": "db",
        "removedownloaded": 0
      },
      {
        "Record": 2,
        "IPaddress": "192.168.6.2",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "\home\config",
        "destfolder": "C:\Users\Sami",
        "filextension": "json",
        "removedownloaded": 1
      },
      {
        "Record": 3,
        "IPaddress": "192.168.6.3",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "\home\config",
        "destfolder": "C:\Users\Sami",
        "filextension": "txt",
        "removedownloaded": 1
      },

    And this is how I add a JSON string every time the user click on ADD.

    private void Button4_Click(object sender, EventArgs e)
            {
                int count = 0;
                if (MessageBox.Show("Are you sure you want to Add", "Add", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
    
                    string filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";
                    string text = File.ReadAllText(filePath);
                    int v = checkBox1.Checked ? 1 : 0;
                    
                    var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
    
                    //Create new Datalogger
    
                    Datalogger myself = new Datalogger
    
                    {
                        Record = currentList.Count + 1,
                        IPaddress = textBox2.Text,
                        Machinename = textBox8.Text,
                        username = textBox4.Text,
                        password = textBox3.Text,
                        sourcefolder = textBox7.Text,
                        destfolder = textBox6.Text,
                        filextension = textBox5.Text,
                        removedownloaded = v
    
    
                    };
    
    
                    if (currentList != null && currentList.Any())
                    {
                        var lastRecordNumner = currentList.OrderBy(q => q.Record).Last().Record;
                        myself.Record = lastRecordNumner + 1;
    
                    }
                    else
                    {
                        currentList = new List<Datalogger>();
                    }
    
                    currentList.Add(myself);
                    string output_Add = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
                    Console.WriteLine(output_Add);
                    File.WriteAllText(filePath, output_Add);
                }
                else
                {
                    this.Activate();
                }
    
    
            }

    To update the JSON I have tried to create a new JSON string and saving it to the selected one by the user. But the string stay the same and it doesn't change.

    private void Button1_Click(object sender, EventArgs e)
            {
                int count = 0;
                if (MessageBox.Show("Are you sure you want to Add", "Add", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    
                    int v = checkBox1.Checked ? 1 : 0;
                   
                    int record = Convert.ToInt32(textBox1.Text);
                    //DataLogger logger = currentList.FirstOrDefault(x => x.Record == record);
                   
                    if (currentList != null)
                    {
    
                        
                        var item2 = currentList.Where(x => x.Record.ToString() == textBox1.Text
                            && x.IPaddress == textBox2.Text
                            && x.Machinename == textBox8.Text
                            && x.username == textBox4.Text
                            && x.password == textBox3.Text
                            && x.sourcefolder == textBox7.Text
                            && x.destfolder == textBox6.Text
                            && x.filextension == textBox5.Text).FirstOrDefault();
    
                        var logger = currentList.Where(m => m.Record == record).FirstOrDefault();
                        //DataLogger logger = currentList.Where(z => z.Record == record).FirstOrDefault();
                        textBox1.Text = logger.Record.ToString();
                        textBox2.Text = logger.IPaddress;
                        textBox8.Text = logger.Machinename;
                        textBox4.Text = logger.username;
                        textBox3.Text = logger.password;
                        textBox7.Text = logger.sourcefolder;
                        textBox6.Text = logger.destfolder;
                        textBox5.Text = logger.filextension;
    
                       
                        // Save everything
                        string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
                        Console.WriteLine(output);
                        File.WriteAllText(filePath, output);
                    }
                    else
                    {
                        currentList = new List<DataLogger>();
                    }  
                }
                else
                {
                    this.Activate();
                }
            }

    Any thoughts? 

    Thanks in advance.

    Friday, August 2, 2019 11:54 AM

Answers

  • Hi samiarja, 

    Thank you for posting here.

    For your question, you find that the script is not taking the new entries after saving new entries back to the same string.

    I make a test on my side based on your code, and it successfully changes the data in the json file.

    Here’s the code.

            /// <summary>
            /// Save the data
            /// </summary>
            private void Button4_Click(object sender, EventArgs e)
            {
                if (MessageBox.Show("Are you sure you want to Save?", "Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string filePath = @"your path";
                    string text = File.ReadAllText(filePath);
    
                    List<Datalogger> currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                    Datalogger logger = currentList.Where(m => m.Record == Convert.ToInt32(textBox1.Text)).FirstOrDefault();
                    logger.IPaddress = textBox2.Text;
                    logger.Machinename = textBox8.Text;
                    logger.username = textBox4.Text;
                    logger.password = textBox3.Text;
                    logger.sourcefolder = textBox7.Text;
                    logger.destfolder = textBox6.Text;
                    logger.filextension = textBox5.Text;
    
                    string output_Add = JsonConvert.SerializeObject(currentList, Formatting.Indented);
                    MessageBox.Show(output_Add);
                    File.WriteAllText(filePath, output_Add);
                }
                else
                {
                    this.Activate();
                }
            }
            /// <summary>
            /// Search data in the json file by the value of textbox1(Record) 
            /// </summary>
            private void Button1_Click(object sender, EventArgs e)
            {
                string filePath = @"your path";
                string text = File.ReadAllText(filePath);
    
                List<Datalogger> currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
        
                int record = Convert.ToInt32(textBox1.Text);
    
                if (currentList != null)
                {
                    Datalogger logger = currentList.Where(m => m.Record == record).FirstOrDefault();
                    textBox2.Text = logger.IPaddress;
                    textBox8.Text = logger.Machinename;
                    textBox4.Text = logger.username;
                    textBox3.Text = logger.password;
                    textBox7.Text = logger.sourcefolder;
                    textBox6.Text = logger.destfolder;
                    textBox5.Text = logger.filextension;
                }
                else
                {
                    MessageBox.Show("No data");
                }
            }

    Result of my test:

    Search data by the value of textbox1:

    Change the data and save it:

    Data in the json file after the test:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by samiarja Monday, August 5, 2019 9:51 AM
    Monday, August 5, 2019 6:47 AM
    Moderator

All replies

  • Hello,

    Your problem is not with JSON.

    You simply didn't update a currentList.


    Sincerely, Highly skilled coding monkey.

    Friday, August 2, 2019 12:30 PM
  • Any thoughts on how to fix that?
    Friday, August 2, 2019 12:53 PM
  • Hi samiarja, 

    Thank you for posting here.

    For your question, you find that the script is not taking the new entries after saving new entries back to the same string.

    I make a test on my side based on your code, and it successfully changes the data in the json file.

    Here’s the code.

            /// <summary>
            /// Save the data
            /// </summary>
            private void Button4_Click(object sender, EventArgs e)
            {
                if (MessageBox.Show("Are you sure you want to Save?", "Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string filePath = @"your path";
                    string text = File.ReadAllText(filePath);
    
                    List<Datalogger> currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                    Datalogger logger = currentList.Where(m => m.Record == Convert.ToInt32(textBox1.Text)).FirstOrDefault();
                    logger.IPaddress = textBox2.Text;
                    logger.Machinename = textBox8.Text;
                    logger.username = textBox4.Text;
                    logger.password = textBox3.Text;
                    logger.sourcefolder = textBox7.Text;
                    logger.destfolder = textBox6.Text;
                    logger.filextension = textBox5.Text;
    
                    string output_Add = JsonConvert.SerializeObject(currentList, Formatting.Indented);
                    MessageBox.Show(output_Add);
                    File.WriteAllText(filePath, output_Add);
                }
                else
                {
                    this.Activate();
                }
            }
            /// <summary>
            /// Search data in the json file by the value of textbox1(Record) 
            /// </summary>
            private void Button1_Click(object sender, EventArgs e)
            {
                string filePath = @"your path";
                string text = File.ReadAllText(filePath);
    
                List<Datalogger> currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
        
                int record = Convert.ToInt32(textBox1.Text);
    
                if (currentList != null)
                {
                    Datalogger logger = currentList.Where(m => m.Record == record).FirstOrDefault();
                    textBox2.Text = logger.IPaddress;
                    textBox8.Text = logger.Machinename;
                    textBox4.Text = logger.username;
                    textBox3.Text = logger.password;
                    textBox7.Text = logger.sourcefolder;
                    textBox6.Text = logger.destfolder;
                    textBox5.Text = logger.filextension;
                }
                else
                {
                    MessageBox.Show("No data");
                }
            }

    Result of my test:

    Search data by the value of textbox1:

    Change the data and save it:

    Data in the json file after the test:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by samiarja Monday, August 5, 2019 9:51 AM
    Monday, August 5, 2019 6:47 AM
    Moderator
  • Hi Xingyu Zhao,

    Thanks so much for your solution and clear instructions. I didn't realise that the json is not deserialized before writing to it.

    I appreciate it so much.

    Monday, August 5, 2019 9:57 AM