c# - 使用 ASP.NET Core 3,如何使 json 响应不序列化复杂类型?
问题描述
我有这个模型:
public class Product
{
public Product()
{
this.Supplier = new Supplier();
}
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int SupplierId { get; set; }
public ProductStatus Status { get; set; }
public Supplier Supplier { get; set; }
}
和另一个模型:
public class Supplier
{
public Supplier()
{
this.Products = new List<Product>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public ICollection<Product> Products { get; set; }
}
每当我尝试使用产品模型发送 json 响应时,我都会得到这种结果:
{
"id": 1,
"name": "HP-ENVY 15",
"price": 800,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 1,
"name": "HP",
"address": "Mckinley",
"products": []
}
}
当尝试使用供应商模型发送响应时:
{
"id": 1,
"name": "HP",
"address": "Mckinley",
"products": [
{
"id": 1,
"name": "HP-ENVY 15",
"price": 800,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 12,
"name": "HP-PAVILION 14",
"price": 550,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 13,
"name": "HP-ENVY 17",
"price": 1200.7,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 14,
"name": "Printer xxx-2020",
"price": 300.5,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
},
{
"id": 15,
"name": "Compaq Presario",
"price": 500.8,
"supplierId": 0,
"status": 0,
"supplier": {
"id": 0,
"name": null,
"address": null,
"products": []
}
}
]
}
两个响应都尝试序列化其中的复杂对象,是否可以:
1.) 发送 Product 模型的 json 响应时,它只会显示 Products 及其供应商(不包括该供应商的 products 属性) 2.) 发送 Supplier 模型的 json 响应时,它只会仅显示供应商及其产品(不包括每个产品的供应商属性)
为了实现这一点,我需要在中间件上配置 json 选项吗?或者我应该创建 DTO/类,其中产品模型中引用的供应商复杂对象没有其产品的属性,反之亦然,供应商模型(它没有产品属性)。
注意:我知道最好使用 viewmodel/dtos 进行 json 响应,但在我的示例中,我们只说 Product 和 Model 都不是域类而是视图模型,因为我的主要问题是如何防止 json 阻止序列化对象属性。
解决方案
JSON.net 具有在MaxDepth
一定程度上去实现的属性。
请注意,这将在一定程度上帮助您。它不会识别相同的对象循环依赖,它只会在反序列化的第二级停止。
对于相反的事情(序列化),您可以在序列化时使用 json.net limit maxdepth来扩展JsonTextWriter
推荐阅读
- sparql - 查找应该是实例 sparql 的类;查找恰好有 1 个子类的类
- kotlin - 如何在kotlin中解密由openssl enc -a -e -aes-256-cbc加密的字符串?
- python - 如何添加具有不同 x 值的 y 值?
- python - 使用 CSV.QUOTE_NONNUMERIC 而不引用标题
- r - R: if (stderr < 10 * .Machine$double.eps * max(abs(mx), abs(my))) 中的错误 stop("数据基本不变") :
- blockchain - 如何查明 RSK 交易在 RSK 区块链上被确认的次数?
- php - 在数据表中的文件名和目录中的文件名之间查找文件名匹配
- sudo - 防止 Centos 用户安装未签名的 RPM
- javascript - 在 graphql 中更新/编辑用户数据(不能为不可为空的字段 Mutation.updateUser 返回 null)
- database - 在不降低 job_queue_processes 值的情况下限制 Oracle 调度程序中正在运行的作业数