'implement CRUD functionality with static data using JSON in asp.net core api project

How to do Crud operation on a locally stored json file? For example, I have id, name and roll number. I want to do get, post, put and delete in it using asp.net core Web API. But I should not use database to store the data instead I need to store the data in controller using method and use it to do the http operations. Can any one please help me with some step or code?



Solution 1:[1]

1.Get the json file:

var data = System.IO.File.ReadAllText("C:\\Repos\\test.json");

enter image description here

2.Delete the json file:

if (System.IO.File.Exists(@"C:\Repos\test.json"))
{
    System.IO.File.Delete(@"C:\Repos\test.json");
}

3.Put the json file:

var data = System.IO.File.ReadAllText("C:\\Repos\\test.json");   
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(data);

jsonObj["id"] = 4;

string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);

System.IO.File.WriteAllText("C:\\Repos\\test.json", output);

enter image description here

4.Add new column to the json file:

var data = System.IO.File.ReadAllText("C:\\Repos\\test.json");

var jObj = JObject.Parse(data);
jObj["NewField"] = "value";
var newjson = jObj.ToString(Newtonsoft.Json.Formatting.Indented);

System.IO.File.WriteAllText("C:\\Repos\\test.json", newjson);

enter image description here

Note:

If you use beyond ASP.NET Core 3.x, you need add Newtonsoft support.

Reference: https://stackoverflow.com/a/61400253/11398810

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1