0

I am a beginner, I wrote a code to return data in a list, but I want data to be in json

[HttpGet]
[Route("getproject")]
public List<ProjectModel> GetProjects()
{
    return new List<ProjectModel>()
                {
                    new ProjectModel() { Id = 1, Project_Name = "abc", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" },
                    new ProjectModel() { Id = 2, Project_Name = "def", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" }
    
                };
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M Nasir
  • 1
  • 2
  • 1
    See the top answer here: https://stackoverflow.com/questions/42360139/asp-net-core-return-json-with-status-code You aren't concerned with status codes here but that's an example of returning your result as Json. – topsail Sep 18 '22 at 13:35
  • Your code already returns JSON response. The `List` is automatically serialized to JSON by the framework. – Dimitris Maragkos Sep 18 '22 at 14:31
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Sep 19 '22 at 23:39

1 Answers1

1

You can use JsonResult like:

[HttpGet]
[Route("getproject")]
public JsonResult GetProjects()
{
    var data = new List<ProjectModel>()
                {
                    new ProjectModel() { Id = 1, Project_Name = "abc", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" },
                    new ProjectModel() { Id = 2, Project_Name = "def", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" }
    
                };

    return Json(data);
}

Or you can use json serializer in namespace:

using System.Text.Json
[HttpGet]
[Route("getproject")]
public IActionResult GetProjects()
{
    var data = new List<ProjectModel>()
                {
                    new ProjectModel() { Id = 1, Project_Name = "abc", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" },
                    new ProjectModel() { Id = 2, Project_Name = "def", Description = "1st project", Type = "plot", SA_Universe_Code = "@ff" }
    
                };

    var serializedData = JsonSerializer.Serialize(data);

    return Ok(serializedData);
}
Rambodsm
  • 127
  • 6