What you can do is that you create a web api to upload json files to it. Refer File Upload Web API.
Next, in the api you read this uploaded file's information using StreamReader whose code you have already shown.
How to write to an existing json file stored in local disk using webapi in ASP.NET Web API?
JSON file:
{
"Students": [
{
"id": 1,
"name": "Ravi",
"department": "IT"
},
{
"id": 2,
"name": "Raj",
"department": "hr"
},
{
"id": 3,
"name": "avi",
"department": "it"
},
{
"id": 4,
"name": "rome",
"department": "HR"
},
{
"id":5,
"name": "virat",
"department": "HR"
},
{
"id":6 ,
"name": "Tushar",
"department": "RM"
}
]
}
I'm trying to read and write data to an existing JSON fil using an ASP.NET Web API. And then will consume this API in an ASP.NET MVC application.
Classes:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
public class Students
{
public List<Student> students { get; set; }
}
ApiController is getting data from an existing JSON file.
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
[HttpGet("JSONFile")]
public Students GetUser()
{
using (StreamReader r = new StreamReader("C:/Users/tanmay_pawar/source/repos/CRUDAPI/CRUDAPI/output.json"))
{
string json = r.ReadToEnd();
Students item = JsonConvert.DeserializeObject<Students>(json);
return item;
}
return new Students();
}
}
2 answers
Sort by: Most helpful
-
Yogi 346 Reputation points
2022-09-04T11:21:26.91+00:00 -
Bruce (SqlWork.com) 55,041 Reputation points
2022-09-04T17:44:18.837+00:00 Implementing json patch via a webapi is a good option
I’d use GET to fetch the whole json, POST write a new json and PATCH to do the patch operation.