none
How to iterate through a JSON file and move through the string by clicking on a button? RRS feed

  • Question

  • I am building a windows form application in C# that takes user input and save it to JSON file, each user will be on a separate string like below as an example from the code: (I have input random data)

    [
      {
        "Record": 1,
        "IPaddress": "168.192.45.34",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "..../..../....",
        "destfolder": "..../..../....",
        "filextension": "db",
        "removedownloaded": 1
      },
      {
        "Record": 2,
        "IPaddress": "168.192.45.255",
        "Machinename": "nautitech",
        "username": "root",
        "password": "root",
        "sourcefolder": "..../..../....",
        "destfolder": "..../..../....",
        "filextension": "txt",
        "removedownloaded": 0
      }]

    Now each Record will have a number and It will be in a descending order. Each string is linked to a textboxes. As an example below, this is how I add data to the JSON file: (Read JSON file, deserialize it, create a new string, save new data, serialize and write all data to the file)

     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 = ++count,
                        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();
                }
    
    
            }

    In the application there is Forward, Backward, Last, First. When the user click on one of this button, the data from the JSON file will be displayed on the textbox on the application and then the user will have an option to delete, update or add new data. Those are the button that I wish the user to user to see the data.

    So far I have figure out First and last, as they are easy to program. However, I am struggling in Forward, Backward. As this button will have to iterate through the JSON string and have to work everytime the user click on them until they reach the beginning or the end of the string.

    Any Thoughts on how to solve that? I appreciate your time and your advice.


    Monday, July 29, 2019 11:27 PM

Answers

  • Hi samiarja,

    Thank you for posting here.

    Based on your description, you want to implement the Forward and Backward functions.

    I think there is no need to use iterate through a JSON to get it, I suggest that you could get it by using Record.

    I make a simple code, you could have a look.

      private void BtnFirst_Click(object sender, EventArgs e)
            {
                string filePath = @"D:\test.json";
                string text = File.ReadAllText(filePath);
    
                var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                if (currentList != null && currentList.Any())
                {
                    var item = currentList.Where(x =>x.Record==1).FirstOrDefault();
                    textBox1.Text = item.IPaddress;
                    textBox2.Text = item.Machinename;
                    textBox3.Text = item.username;
                    textBox4.Text = item.password;
                    textBox5.Text = item.sourcefolder;
                    textBox6.Text = item.destfolder;
                    textBox7.Text = item.filextension;
    
    
                }
                else
                {
                    currentList = new List<Datalogger>();
                }
    
            }
    
            private void Btnforward_Click(object sender, EventArgs e)
            {
                string filePath = @"D:\test.json";
                string text = File.ReadAllText(filePath);
    
                var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                if (currentList != null && currentList.Any())
                {
                    var item1 = currentList.Where(x => x.IPaddress == textBox1.Text && x.Machinename == textBox2.Text && x.username == textBox3.Text && x.password == textBox4.Text && x.sourcefolder == textBox5.Text && x.destfolder == textBox6.Text && x.filextension == textBox7.Text).FirstOrDefault();
                    var item = currentList.Where(m => m.Record == item1.Record + 1).FirstOrDefault();
                    textBox1.Text = item.IPaddress;
                    textBox2.Text = item.Machinename;
                    textBox3.Text = item.username;
                    textBox4.Text = item.password;
                    textBox5.Text = item.sourcefolder;
                    textBox6.Text = item.destfolder;
                    textBox7.Text = item.filextension;
    
                }
                else
                {
                    currentList = new List<Datalogger>();
                }
            }
    
            private void Btnbackward_Click(object sender, EventArgs e)
            {
                string filePath = @"D:\test.json";
                string text = File.ReadAllText(filePath);
    
                var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                if (currentList != null && currentList.Any())
                {
                    var item1 = currentList.Where(x => x.IPaddress == textBox1.Text && x.Machinename == textBox2.Text && x.username == textBox3.Text && x.password == textBox4.Text && x.sourcefolder == textBox5.Text && x.destfolder == textBox6.Text && x.filextension == textBox7.Text).FirstOrDefault();
                    var item = currentList.Where(m => m.Record == item1.Record-1).FirstOrDefault();
                    textBox1.Text = item.IPaddress;
                    textBox2.Text = item.Machinename;
                    textBox3.Text = item.username;
                    textBox4.Text = item.password;
                    textBox5.Text = item.sourcefolder;
                    textBox6.Text = item.destfolder;
                    textBox7.Text = item.filextension;
    
                }
                else
                {
                    currentList = new List<Datalogger>();
                }
            }

    Note: I lose the removedownloaded field, you could add it.

    Result:

    My json file:

    [
      {
        "Record": 1,
        "IPaddress": "168.192.45.34",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "..../..../....",
        "destfolder": "..../..../....",
        "filextension": "db",
        "removedownloaded": 0
      },
      {
        "Record": 2,
        "IPaddress": "168.192.45.255",
        "Machinename": "nautitech",
        "username": "root",
        "password": "root",
        "sourcefolder": "..../..../....",
        "destfolder": "..../..../....",
        "filextension": "txt",
        "removedownloaded": 0
      },
      {
        "Record": 3,
        "IPaddress": "172.13.16.811",
        "Machinename": "pc",
        "username": "testuser",
        "password": "testpwd",
        "sourcefolder": "c:\\\\",
        "destfolder": "d:\\\\",
        "filextension": ".txt",
        "removedownloaded": 0
      }
    ]

    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.


    Tuesday, July 30, 2019 6:42 AM
    Moderator

All replies

  • Hi samiarja,

    Thank you for posting here.

    Based on your description, you want to implement the Forward and Backward functions.

    I think there is no need to use iterate through a JSON to get it, I suggest that you could get it by using Record.

    I make a simple code, you could have a look.

      private void BtnFirst_Click(object sender, EventArgs e)
            {
                string filePath = @"D:\test.json";
                string text = File.ReadAllText(filePath);
    
                var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                if (currentList != null && currentList.Any())
                {
                    var item = currentList.Where(x =>x.Record==1).FirstOrDefault();
                    textBox1.Text = item.IPaddress;
                    textBox2.Text = item.Machinename;
                    textBox3.Text = item.username;
                    textBox4.Text = item.password;
                    textBox5.Text = item.sourcefolder;
                    textBox6.Text = item.destfolder;
                    textBox7.Text = item.filextension;
    
    
                }
                else
                {
                    currentList = new List<Datalogger>();
                }
    
            }
    
            private void Btnforward_Click(object sender, EventArgs e)
            {
                string filePath = @"D:\test.json";
                string text = File.ReadAllText(filePath);
    
                var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                if (currentList != null && currentList.Any())
                {
                    var item1 = currentList.Where(x => x.IPaddress == textBox1.Text && x.Machinename == textBox2.Text && x.username == textBox3.Text && x.password == textBox4.Text && x.sourcefolder == textBox5.Text && x.destfolder == textBox6.Text && x.filextension == textBox7.Text).FirstOrDefault();
                    var item = currentList.Where(m => m.Record == item1.Record + 1).FirstOrDefault();
                    textBox1.Text = item.IPaddress;
                    textBox2.Text = item.Machinename;
                    textBox3.Text = item.username;
                    textBox4.Text = item.password;
                    textBox5.Text = item.sourcefolder;
                    textBox6.Text = item.destfolder;
                    textBox7.Text = item.filextension;
    
                }
                else
                {
                    currentList = new List<Datalogger>();
                }
            }
    
            private void Btnbackward_Click(object sender, EventArgs e)
            {
                string filePath = @"D:\test.json";
                string text = File.ReadAllText(filePath);
    
                var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);
                if (currentList != null && currentList.Any())
                {
                    var item1 = currentList.Where(x => x.IPaddress == textBox1.Text && x.Machinename == textBox2.Text && x.username == textBox3.Text && x.password == textBox4.Text && x.sourcefolder == textBox5.Text && x.destfolder == textBox6.Text && x.filextension == textBox7.Text).FirstOrDefault();
                    var item = currentList.Where(m => m.Record == item1.Record-1).FirstOrDefault();
                    textBox1.Text = item.IPaddress;
                    textBox2.Text = item.Machinename;
                    textBox3.Text = item.username;
                    textBox4.Text = item.password;
                    textBox5.Text = item.sourcefolder;
                    textBox6.Text = item.destfolder;
                    textBox7.Text = item.filextension;
    
                }
                else
                {
                    currentList = new List<Datalogger>();
                }
            }

    Note: I lose the removedownloaded field, you could add it.

    Result:

    My json file:

    [
      {
        "Record": 1,
        "IPaddress": "168.192.45.34",
        "Machinename": "taurus",
        "username": "root",
        "password": "root",
        "sourcefolder": "..../..../....",
        "destfolder": "..../..../....",
        "filextension": "db",
        "removedownloaded": 0
      },
      {
        "Record": 2,
        "IPaddress": "168.192.45.255",
        "Machinename": "nautitech",
        "username": "root",
        "password": "root",
        "sourcefolder": "..../..../....",
        "destfolder": "..../..../....",
        "filextension": "txt",
        "removedownloaded": 0
      },
      {
        "Record": 3,
        "IPaddress": "172.13.16.811",
        "Machinename": "pc",
        "username": "testuser",
        "password": "testpwd",
        "sourcefolder": "c:\\\\",
        "destfolder": "d:\\\\",
        "filextension": ".txt",
        "removedownloaded": 0
      }
    ]

    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.


    Tuesday, July 30, 2019 6:42 AM
    Moderator
  • Hi Jack, sorry for the late reply.

    Many thanks for your solution. You are providing such really high quality answers and they are always easy to understand.

    Much respect for you and your hard work.

    Cheers,

    Sami

    Thursday, August 1, 2019 10:34 AM
  • Hi Jack, Sorry consistently asking, however, this time I am trying to update some entries when the user click forward backward button by trying to create new list and then write to the JSON file, but the JSON stay the same, and it doesn't seem it is saving anything.

    if (MessageBox.Show("Are you sure you want to Update", "Update", 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();
                }

    Thursday, August 1, 2019 11:05 AM
  • Hi samiarja,

    Thanks for the feedback.

    For your new question, I suggest that you could create a new thread in c# forum because one thread for one question.

    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.

    Friday, August 2, 2019 5:25 AM
    Moderator
  • Hi Jack,

    Thanks for you suggestion.

    no problem at all, I have created a new thread.

    Thanks so much.

    Cheers,

    Sami

    Friday, August 2, 2019 11:56 AM