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
3.4k views
in .Net Framework by 39 42 54

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

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


1 Answer

0 like 0 dislike
by 39 42 54
 
Best answer

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