我有一个模型:
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": []
}
}
]
} 这两个响应都试图序列化它们内部的complext对象,是否可以:
1.)当发送Product模型的json响应时,它将仅显示产品及其供应商(不包括该供应商的产品属性)2。当为供应商模型发送json响应时,它将只显示供应商及其产品(不包括每个产品的供应商属性)。
为了实现这一点,我需要在中间件上配置json选项吗?或者,我应该创建DTO/类,其中在Product模型中引用的Supplier复杂对象没有其产品属性,反之亦然(它没有products属性)。
注意:我知道对json响应最好使用viewmodel/ do,但在我的示例中,让我们只说Product和Model都不是域类,而是viewmodel,因为我的主要问题是如何防止json阻止序列化对象属性。
发布于 2020-03-08 15:14:22
JSON.net具有MaxDepth属性,用于在某个时间点之前进行去中心化。
但要注意,这将在一定程度上帮助您。它不会识别相同的对象循环依赖,它只会在反序列化的第二级停止。
对于相反的事情(序列化),您可以使用json.net limit maxdepth when serializing扩展JsonTextWriter
https://stackoverflow.com/questions/60585187
复制相似问题