0

I have created the employee.json which will have id,firstname and lastname i am try to get the json reponse back, but postman return me an empty json object

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

    public JsonResult Get()
    {

        var jsonFile = System.IO.File.ReadAllText(@"C:\Users\Employee.json");
        List<Employee> employee =  JsonConvert.DeserializeObject<List<Employee>>(jsonFile);
        return new JsonResult(new Employee(1, "Toyota", "Aygo"));
    }
}

here is the employee.json file

[{
  "id": 1,  
  "firstname": "First Employee First Name",
  "lastname": "First Employee Last Name"
  },
  {
  "id": 2,  
  "firstname": "Second Employee First Name",
  "lastname": "Second Employee Last Name"
 }]

Below is the Postman response

enter image description here

1
  • Are your Employee class properties/fields private? Commented Mar 15, 2021 at 5:54

1 Answer 1

1
  1. Check the name of your file Employee.json not employee.json which should be same as codes in controller.

    enter image description here

  2. Set Employee Model as below

public class Employee
{
    public Employee(int id, string firstname, string lastname)
    {
        this.Id = id;
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

Codes of Controller

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

    public JsonResult Get()
    {
        var jsonFile = System.IO.File.ReadAllText(@"D:\Users\Employee.json");
        List<Employee> employee = JsonConvert.DeserializeObject<List<Employee>>(jsonFile);
        //return new JsonResult(new Employee(1, "Toyota", "Aygo"));

        return new JsonResult(employee);
    }
}

Result enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.