Http请求如何返回对象列表

Eli*_*099 2 c# api http

所以我已经从使用 Java 转向使用 C#,并且 Spring boot 与 C# 不同。我正在尝试使用 mongodb 数据库将对象列表返回到 REST API。但结果不返回列表,而是返回一些包含我的列表的对象。

品牌类

[BsonIgnoreExtraElements]
public class Brand
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string _id { get; set; }
    public string name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器

[HttpGet("getAllBrands")]
public async Task<IActionResult> Get()
{
    var brands = await _brandRepository.getAllBrands();

    List<Brand> list = (List<Brand>) brands;

    return new JsonResult(list);
} 
Run Code Online (Sandbox Code Playgroud)

品牌库

public async Task<IEnumerable<Brand>> getAllBrands()
{
    var brands = await _brands.Find(_ => true).ToListAsync();
    return brands;
}
Run Code Online (Sandbox Code Playgroud)

我的期望是什么

[
      {
        "_id": "60d235f60f8c98376ba5b67d",
        "name": "Some brand 1"
      },
      {
        "_id": "60d24d6b0f8c98376ba5b68c",
        "name": "Some brand 2"
      },
      {
        "$id": "6",
        "_id": "60d24e4b0f8c98376ba5b68d",
        "name": "Some brand 3"
      }
    ]
Run Code Online (Sandbox Code Playgroud)

我实际上得到了什么

{
  "$id": "1",
  "$values": [
    {
      "$id": "2",
      "_id": "60d235f60f8c98376ba5b67d",
      "name": "Some brand 1"
    },
    {
      "$id": "4",
      "_id": "60d24d6b0f8c98376ba5b68c",
      "name": "Some brand 2"
    },
    {
      "$id": "6",
      "_id": "60d24e4b0f8c98376ba5b68d",
      "name": "Some brand 1"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我如何只返回一个简单的对象列表作为结果而不是那个?谢谢

dev*_*ull 5

当您的 JSON 序列化程序设置为保留引用时,您看到的 JSON 是预期的。这样,就可以添加元数据成员 ( $id$ref$values),以便可以在 JSON 中引用对象,而不是重复对象。

更具体地说(参见ReferenceHandler.Preserve):

对于可枚举类型(例如 List),JSON 数组必须按顺序嵌套在包含 $id 和 $values 元数据属性的 JSON 对象中

这可能是在您的应用程序启动时配置的,例如:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddJsonOptions(options => 
           options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
}
Run Code Online (Sandbox Code Playgroud)

要获得预期的 JSON,您需要禁用此功能。您可以像以前一样在应用程序启动时执行此操作:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddJsonOptions(options => 
           options.JsonSerializerOptions.ReferenceHandler = null);
}
Run Code Online (Sandbox Code Playgroud)

或者仅针对该特定端点:

[HttpGet("getAllBrands")]
public async Task<IActionResult> Get()
{
    var brands = await _brandRepository.getAllBrands();

    List<Brand> list = (List<Brand>) brands;

    return new JsonResult(list, new JsonSerializerOptions
    {
        ReferenceHandler = null,
        WriteIndented = true
    });
}
Run Code Online (Sandbox Code Playgroud)