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

I am working on mvc application and i want to update item from json file using c# Like below example.
 

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

 


1 Answer

1 like 0 dislike
by 39 42 54
 
Best answer

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