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

    }  

}

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,141 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,247 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,206 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Yogi 346 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) 55,041 Reputation points
    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