gpt4 book ai didi

c# - Http请求如何返回对象列表

转载 作者:行者123 更新时间:2023-12-02 02:06:12 24 4
gpt4 key购买 nike

所以我已经从使用 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; }
}

Controller

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

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

return new JsonResult(list);
}

品牌库

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

我的期望

[
{
"_id": "60d235f60f8c98376ba5b67d",
"name": "Some brand 1"
},
{
"_id": "60d24d6b0f8c98376ba5b68c",
"name": "Some brand 2"
},
{
"$id": "6",
"_id": "60d24e4b0f8c98376ba5b68d",
"name": "Some brand 3"
}
]

我实际上得到了什么

{
"$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"
}
]
}

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

最佳答案

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

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

For enumerable types, such as List, the JSON array must be nested within a JSON object containing an $id and $values metadata property, in that order

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

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
}

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

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.ReferenceHandler = null);
}

或者仅针对该特定端点:

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

关于c# - Http请求如何返回对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68430194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com