Home > OS >  stream writer is not writing to JSON file in webapi
stream writer is not writing to JSON file in webapi

Time:09-06

Im trying to write data in a JSON file using webapi but stream writer is not writing data to the file.

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"
 }
]
}

Class

     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; }
}   

Api controller: [HttpPost] method for writing data to the json file.

    [Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{

  [HttpPost]
    public IActionResult Add(Students _Student)
    {        
        using (var fs = new FileStream("C:/Users/tanmay_pawar/source/repos/CRUDAPI/CRUDAPI/people.json", FileMode.Append))
         using (var sw = new StreamWriter(fs))
        {
           sw.WriteLine(_Student);
        }

}

The data recieved in by _Student is not getting added to the json file.

CodePudding user response:

try this

public IActionResult Add(Students _Student)
{
      if(_Student==null || _Student.students==null)  return null;

    var filePath = @"C:\Users\....\..json";
    var json = File.ReadAllText(filePath);
    
    Students students = JsonConvert.DeserializeObject<Students>(json);
  
    students.students.AddRange(_Student.students);
    
    json=JsonConvert.SerializeObject(students);
    File.WriteAllText(filePath, json);
}

CodePudding user response:

Try the code like below:

        [HttpPost]
        public IActionResult Add(Students _Student)
        {
            string jsonresult = JsonConvert.SerializeObject(_Student);

            string path = @"C:\c\people.json";

          
            using(var tw=new StreamWriter(path,true))
            {
                tw.WriteLine(jsonresult.ToString());
                tw.Close();
            }

            return Ok();
}

result:

enter image description here

enter image description here

  • Related