Asp.Net Core Web Api、Json 对象不返回复杂对象中的子对象

dev*_*nje 6 c# asp.net-mvc asp.net-core asp.net-core-webapi

我有 Asp.Net core 3.1 Web Api,其中复杂的对象应该由 Json 之类的操作返回,问题是返回的对象不包含子对象列表:

对象下方:

public class DepartementViewModel
{
    public int Dep_ID { get; set; }
    public string Dep_Name { get; set; }

    public List<BasicEmpViewModel> listEmployees = new List<BasicEmpViewModel>();
}
Run Code Online (Sandbox Code Playgroud)

和行动

[HttpGet]
public async Task<ActionResult<IEnumerable<DepartementViewModel>>> GetDepartement()
{
    IRepository IRepos = new DepartementRepository(_context);
    IList<DepartementViewModel> ilIst = await IRepos.GetList();
    return Ok(ilIst);
}
Run Code Online (Sandbox Code Playgroud)

存储库 GetList 函数

public async Task<IList<DepartementViewModel>> GetList()
{
    IList<DepartementViewModel> listDept = new List<DepartementViewModel>();
    listDept = await(from dept in _context.Departement                        
                          orderby dept.Dep_ID ascending
                              select new DepartementViewModel
                              {
                                  dept.Dep_ID ,
                                  dept.Dep_Name
                              }
                     ).ToListAsync();

    listDept.ForEach(x =>
    {       
        var emObj =_context.Employee;
        foreach (Employee E in emObj)
        {
            E.listEmployees.Add(new BasicEmpViewModel()
                                    {
                                        Emp_ID = E.Emp_ID,
                                        Emp_Name = E.Emp_Name,
                                        Checked = (E.Dep_ID == x.Dep_ID) ? true : false
                                    }
                                );
        }
    }); 

    return listDept;
}
Run Code Online (Sandbox Code Playgroud)

返回的 Json 对象不包含员工列表“listEmployees”,它仅显示与主对象:Dep_ID 和 Dep_Name 相关的信息。

我的代码中是否缺少某些内容?

谢谢

dev*_*nje 7

我已经找到了解决方案,我发布了任何此类问题的解决方案。事实上,有必要在 DepartementViewModel 类中为属性 listEmployees 放置一个 Getter 和 Setter,如下所示

public class DepartementViewModel
{
    public int Dep_ID { get; set; }
    public string Dep_Name { get; set; }

    public List<BasicEmpViewModel> listEmployees {get; set; };
}
Run Code Online (Sandbox Code Playgroud)

亲切地


Zhi*_* Lv 3

我想也许您正在使用System.Text.Json库来序列化和反序列化 .net core 应用程序中的数据,对吗?如果是这样的话,问题可能与这个库有关。据我所知,当我们使用该System.Text.Json库序列化复杂对象时,它只会返回外部对象(没有内部实体)。

为了解决这个问题,您可以尝试使用该Microsoft.AspNetCore.Mvc.NewtonsoftJson库来序列化数据。请参考以下步骤:

  1. Microsoft.AspNetCore.Mvc.NewtonsoftJson通过 Nuget安装包。

  2. NewtonsoftJson在 Startup.ConfigureServices 方法中注册:

         services.AddControllersWithViews().AddNewtonsoftJson();
    
    Run Code Online (Sandbox Code Playgroud)

以下是一些关于System.Text.Json和 的相关文章Microsoft.AspNetCore.Mvc.NewtonsoftJson,您可以参考:

如何在 .NET 中序列化和反序列化(编组和解组)JSON

如何从 Newtonsoft.Json 迁移到 System.Text.Json