【问题标题】:Postman return empty Json result web api邮递员返回空的 Json 结果 web api
【发布时间】:2021-03-15 13:58:39
【问题描述】:

我创建了包含 id、firstname 和 lastname 的employee.json 我试图找回 json 响应,但邮递员返回给我一个空的 json 对象

[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"));
    }
}

这里是employee.json 文件

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

以下是邮递员的回复

【问题讨论】:

  • 您的Employee 类属性/字段是私有的吗?

标签: asp.net-core-webapi asp.net-core-3.1


【解决方案1】:
  1. 检查你的文件名Employee.json 不是employee.json 这应该与控制器中的代码相同。

  2. 设置Employee型号如下

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

控制器代码

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

结果

【讨论】:

    猜你喜欢
    • 2022-07-11
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多