Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
1.2k views
in .Net Framework by 36 42 54
edited by

I am working on the MVC application and I want to Delete items from JSON file using c# Like the below example.

{
  "CheckListScenario": [
    {
      "URL": "http://google.com",
      "Key": "Google"
    },
    {
      "URL": "http://facebook.com",
      "Key": "FaceBook"
    }
  ]
}

 


1 Answer

0 like 0 dislike
by 36 42 54
edited by
 
Best answer

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;
     }
If you don’t ask, the answer is always NO!
...