Delete item from json file
To delete item from 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/test.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) Find the item with the specified key and delete it
var itemToDelete = jsonObject.CheckListScenario.Find(item => item.Key == "keyToDelete");
keyToDelete : Like FaceBook or Google
7) Remove the item from the list
jsonObject.CheckListScenario.Remove(itemToDelete);
8) Serialize the updated object back to JSON
string updatedJson = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
9) 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);
string keyToDelete = Key;
var itemToDelete = jsonObject.CheckListScenario.Find(item => item.Key == keyToDelete);
if (itemToDelete != null)
{
jsonObject.CheckListScenario.Remove(itemToDelete);
string updatedJson = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
File.WriteAllText(filePath, updatedJson);
return true;
}
else
{
throw;
}