How to write to an existing json file stored in local disk using webapi in ASP.NET Web API?

Tanmay Vijay Pawar 1 Reputation point
2022-09-04T08:08:40.477+00:00

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();

    }  

}

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET Other
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Yogi 351 Reputation points
    2022-09-04T11:21:26.91+00:00

    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.

    0 comments No comments

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-09-04T17:44:18.837+00:00

    Implementing json patch via a webapi is a good option

    https://jsonpatch.com/

    I’d use GET to fetch the whole json, POST write a new json and PATCH to do the patch operation.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.