I have created a sample project to read json file, edit and save into another file using c# and Newtonsoft.Json library. If anyone want this kind of implementation, you can download project and continue. I have added the sample json file with the project into my Github repository.
I have json file format like below.
{ "tasks": [{ "AccountName": "testaccount", "AccountKey": "0de5edbc-6a02-4450-a139-33d4e760a257", "ContainerName": "1234", "RootPath": "/", "DaysOfHistoryToKeep": 10 }, { "AccountName": "test2", "AccountKey": "f15c414b-734a-4a4e-b1a6-eb0794df4e46", "ContainerName": "2345", "RootPath": "/", "DaysOfHistoryToKeep": 15 }] }
According to that json structure, i am going to build my object structure like below.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JsonEditor { public class Task { public string AccountName { get; set; } public string AccountKey { get; set; } public string ContainerName { get; set; } public string RootPath { get; set; } public int DaysOfHistoryToKeep { get; set; } } }
And I have Tasks
class which contains list of Task
classes.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JsonEditor { public class Tasks { public List<Task> tasks { get; set; } } }
This is how program going to read the json file and convert into list and bind into grid.
Stream myStream = null; OpenFileDialog theDialog = new OpenFileDialog(); theDialog.Title = "Open Text File"; theDialog.Filter = "JSON files|*.json"; theDialog.InitialDirectory = @"C:\"; if (theDialog.ShowDialog() == DialogResult.OK) { try { if (theDialog.FileName.Trim() != string.Empty) { using (StreamReader r = new StreamReader(theDialog.FileName)) { string json = r.ReadToEnd(); Tasks items = JsonConvert.DeserializeObject(json); dgTasks.DataSource = items.tasks; } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } }
And convert grid data into json file.
Tasks tasks = new Tasks(); tasks.tasks = (List)dgTasks.DataSource; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.InitialDirectory = @"C:\"; saveFileDialog1.Filter = "JSON Image|*.json"; saveFileDialog1.Title = "Save a JSON File"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { File.WriteAllText(saveFileDialog1.FileName, JsonConvert.SerializeObject(tasks)); }
Please download the project and use it in your projects. You have to add exception handling into this project.
Loved your code, and I would also suggests https://jsonformatter.org/json-editor