Add new item into json file
To add new item into json file, you should follow the below steps in details:
1) Create new json file with name test.json
2) Add path of file in web.config
<appSettings>
<add key="jsonPath" value="E:/CheckList/Mofa.CheckList/checkList.json" />
</appSettings>
3) Read path from web.config
string filePath = ConfigurationManager.AppSettings["jsonPath"];
4) Read the existing JSON content from the file
string jsonContent = File.ReadAllText(filePath);
5) Deserialize the JSON into a C# object
var jsonObject = JsonConvert.DeserializeObject<CheckListScenarioTest>(jsonContent);
6) Adding a new item into json file
jsonObject.CheckListScenario.Add(new ScenarioItem { URL = item.URL, Key = item.Key });
7) Serialize the updated object to JSON format
string updatedJson = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
8) Write the updated JSON content to the file
File.WriteAllText(filePath, updatedJson);
Code
string filePath = ConfigurationManager.AppSettings["jsonPath"];
string jsonContent = File.ReadAllText(filePath);
var jsonObject = JsonConvert.DeserializeObject<CheckListScenarioTest>(jsonContent);
jsonObject.CheckListScenario.Add(new ScenarioItem { URL = item.URL, Key = item.Key });
string updatedJson = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
File.WriteAllText(filePath, updatedJson);