Update item from json file
To update 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 update it
var itemToEdit = jsonObject.CheckListScenario.Find(item => item.Key.Equals(OldKey));
OldKey : Like FaceBook or Google
7) Check if itemToEdit is null or not before updating item from the list
if (itemToEdit != null)
{}
8) Modify the item properties
itemToEdit.URL = NewURL;
9) Serialize the updated object back to JSON
string updatedJson = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
10) 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);
var itemToEdit = jsonObject.CheckListScenario.Find(item => item.Key.Equals(OldKey) || item.URL.Equals(OldURL));
if (itemToEdit != null)
{
itemToEdit.URL = NewURL;
itemToEdit.Key = NewKey;
string updatedJson = JsonConvert.SerializeObject(jsonObject, Formatting.Indented);
File.WriteAllText(filePath, updatedJson);
return true;
}
else
{
return false;
}