none
How to delete and update a JSON string and bind it to a button? RRS feed

  • Question

  • I am creating an application in C# windows form. This application will allow the user to enter data and then click "ADD" button, then this data will go to a structured JSON file. Now the user might need to delete one of the entries they made, therefore I have added a "Delete" and "Save" button to allow to user to delete and update the JSON string when needed. 

    Below is an example of the JSON file

    
    
    
    
    [
      {
        "Record": 1,
        "IPaddress": "192.148.34.34",
        "Machinename": "user",
        "username": "root",
        "password": "root",
        "sourcefolder": ".../.../...",
        "destfolder": ".../.../...",
        "filextension": "db",
        "removedownloaded": 0
      },
      {
        "Record": 2,
        "IPaddress": "255.255.255.255",
        "Machinename": "datalog",
        "username": "root",
        "password": "root",
        "sourcefolder": "././././",
        "destfolder": "./././.",
        "filextension": "json",
        "removedownloaded": 0
      }
    ]

    This is how the JSON string is created 

    class Datalogger
            {
                public int Record
                {
                    get;
                    set;
                }
                public string IPaddress
                {
                    get;
                    set;
                }
                public string Machinename
                {
                    get;
                    set;
                }
                public string username
                {
                    get;
                    set;
                }
                public string password
                {
                    get;
                    set;
                }
                public string sourcefolder
                {
                    get;
                    set;
                }
                public string destfolder
                {
                    get;
                    set;
                }
                public string filextension
                {
                    get;
                    set;
                }
                public int removedownloaded
                {
                    get;
                    set;
                }
                

    Below is how the JSON string is re-created everytime the user enter new data.

    private void button4_Click(object sender, EventArgs e)
            {
                if (MessageBox.Show("Are you sure you want to Add", "ADD", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                  
                    filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";
                    // Update json data string
                    //jsonData = JsonConvert.SerializeObject(DataloggerList);
                    //System.IO.File.WriteAllText(filePath, jsonData);
                    string text = File.ReadAllText(filePath);
    
                    var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
    
                    //Create new Datalogger
    
                    Datalogger myself = new Datalogger
    
                    {
    
                        Record = ++count,
                        IPaddress = textBox2.Text,
                        Machinename = textBox8.Text,
                        username = textBox4.Text,
                        password = textBox3.Text,
                        sourcefolder = textBox7.Text,
                        destfolder = textBox6.Text,
                        filextension = textBox5.Text,
    
                    };
    
                    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 = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
                    Console.WriteLine(output);
                    File.WriteAllText(filePath, output);
                }
                else
                {
                    this.Activate();
                }
    
    
            }

    Any thoughts on how to bind delete and save button to the JSON file to delete the string or update it.

    I appreciate any idea, and thanks in advance.

    Monday, July 29, 2019 12:33 AM

Answers

  • You should have passed "the list item that matches the item you want to delete" to .Remove() right? Why would it remove the entire list?

    It should be something like this (just type it out of my mind, not verified on compiler):

    var item = currentList.Where(x => 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();

    if (item != null)
    {
        currentList.Remove(item);
    }

    Since your "Record" field is moving, I will not use it as criteria here. Judge it yourself whether you need to compare all other fields as I shown here or there are some fields that need not be compared.


    • Edited by cheong00Editor Monday, July 29, 2019 6:16 AM
    • Marked as answer by samiarja Monday, July 29, 2019 11:31 PM
    Monday, July 29, 2019 6:16 AM
    Answerer
  • Hi samiarja,

    Thank you for posting here.

    I think cheong00's solution is right, which could help you delete the json string in json file.

    >>What is x in this case

    It is a linq query sentence, x is a parameter. Its role here is to filter the items that match the string in the textbox.

    You could try the following code to delete the json string in json file.

      private void Button2_Click(object sender, EventArgs e)
            {
                int count = 0;
                if (MessageBox.Show("Are you sure you want to delete", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
    
                    string filePath = @"D:\test.json";
                    string text = File.ReadAllText(filePath);
    
                    var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
    
                    //Create new Datalogger
    
                    Datalogger myself = new Datalogger
    
                    {
    
                        Record = ++count,
                        IPaddress = textBox1.Text,
                        Machinename = textBox2.Text,
                        username = textBox3.Text,
                        password = textBox4.Text,
                        sourcefolder = textBox5.Text,
                        destfolder = textBox6.Text,
                        filextension = textBox7.Text,
    
                    };
    
                    if (currentList != null && currentList.Any())
                    {
                        var item = currentList.Where(x => x.IPaddress == textBox1.Text&& x.Machinename == textBox2.Text&& x.username == textBox3.Text&& x.password == textBox3.Text&& x.sourcefolder == textBox4.Text&& x.destfolder == textBox5.Text&& x.filextension == textBox6.Text).FirstOrDefault();
                        if (item != null)
                        {
                            currentList.Remove(item);
                        }
    
                    }
                    else
                    {
                        currentList = new List<Datalogger>();
                    }
    
                    //currentList.Add(myself);
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
                    Console.WriteLine(output);
                    File.WriteAllText(filePath, output);
                }
                else
                {
                    this.Activate();
                }
            }

    Result:

    Best Regards,

    Jack


    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.



    Monday, July 29, 2019 7:09 AM
    Moderator

All replies

  • Usually you kept your data in List<T> or DataTable, and covert it to JSON on need.

    Search and replace character sequences in string is expensive operation, search and delete an entry on List<T> or DataTable is much less expensive one. 

    Monday, July 29, 2019 1:26 AM
    Answerer
  • Thanks for your reply, could you please show me an implementation example? It's hard for me to visualize the implementation

     I really appreciate it

    Monday, July 29, 2019 1:45 AM
  • I mean, referring to your code, you should aways keep

    List<Datalogger> currentList

    in memory, perheps as a variable in global log handler class.

    When there is change to data, you can decide whether to convert it to JSON and save it right away, or to leave it until the end of process and save only when the program exit.

    Depending on whether it's online-editing of data, you may want to have code peek whether the file size has changed before saving. If so you may want to reload the data from JSON to currentList, delete the record by key fields, then write back the currentList to file in JSON format.

    Monday, July 29, 2019 2:37 AM
    Answerer
  • What's the syntax for saving and deleting a Json string, I somehow couldn't manage to implement these two operations
    Monday, July 29, 2019 4:40 AM
  • To remove an element from your list you can call currentList.Remove().

    To save, your own code already has it:

    string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
                   
    Console.WriteLine(output);
                   
    File.WriteAllText(filePath, output);

    Monday, July 29, 2019 5:45 AM
    Answerer
  • I have tried currentList.Remove(), but it deleted all the JSON string and make the file empty, I need to delete one string at a time.

    how to delete by indexing?


    • Edited by samiarja Monday, July 29, 2019 5:56 AM bold text
    Monday, July 29, 2019 5:55 AM
  • You should have passed "the list item that matches the item you want to delete" to .Remove() right? Why would it remove the entire list?

    It should be something like this (just type it out of my mind, not verified on compiler):

    var item = currentList.Where(x => 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();

    if (item != null)
    {
        currentList.Remove(item);
    }

    Since your "Record" field is moving, I will not use it as criteria here. Judge it yourself whether you need to compare all other fields as I shown here or there are some fields that need not be compared.


    • Edited by cheong00Editor Monday, July 29, 2019 6:16 AM
    • Marked as answer by samiarja Monday, July 29, 2019 11:31 PM
    Monday, July 29, 2019 6:16 AM
    Answerer
  • Sorry for asking too many question, I just want to understand it.

    What is x in this case, it doesn't seem that is doing anything to the JSON string, I might be wrong. can you please explain how I can select the string number from the json file using this method?

    Monday, July 29, 2019 6:46 AM
  • Hi samiarja,

    Thank you for posting here.

    I think cheong00's solution is right, which could help you delete the json string in json file.

    >>What is x in this case

    It is a linq query sentence, x is a parameter. Its role here is to filter the items that match the string in the textbox.

    You could try the following code to delete the json string in json file.

      private void Button2_Click(object sender, EventArgs e)
            {
                int count = 0;
                if (MessageBox.Show("Are you sure you want to delete", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
    
                    string filePath = @"D:\test.json";
                    string text = File.ReadAllText(filePath);
    
                    var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
    
                    //Create new Datalogger
    
                    Datalogger myself = new Datalogger
    
                    {
    
                        Record = ++count,
                        IPaddress = textBox1.Text,
                        Machinename = textBox2.Text,
                        username = textBox3.Text,
                        password = textBox4.Text,
                        sourcefolder = textBox5.Text,
                        destfolder = textBox6.Text,
                        filextension = textBox7.Text,
    
                    };
    
                    if (currentList != null && currentList.Any())
                    {
                        var item = currentList.Where(x => x.IPaddress == textBox1.Text&& x.Machinename == textBox2.Text&& x.username == textBox3.Text&& x.password == textBox3.Text&& x.sourcefolder == textBox4.Text&& x.destfolder == textBox5.Text&& x.filextension == textBox6.Text).FirstOrDefault();
                        if (item != null)
                        {
                            currentList.Remove(item);
                        }
    
                    }
                    else
                    {
                        currentList = new List<Datalogger>();
                    }
    
                    //currentList.Add(myself);
                    string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
                    Console.WriteLine(output);
                    File.WriteAllText(filePath, output);
                }
                else
                {
                    this.Activate();
                }
            }

    Result:

    Best Regards,

    Jack


    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.



    Monday, July 29, 2019 7:09 AM
    Moderator
  • Thank you all Cheong00 and Jack J Jun for providing me with these valuable information and visualizations. Without you guys I will be stuck for hours. You guys deserve gold medal, I appreciate it.

    The problem is solved and I can now work on other tasks :) 

     
    Monday, July 29, 2019 10:19 PM