首页 > 解决方案 > 使用 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 阻止序列化对象属性。

标签: c#jsonasp.net-mvcasp.net-core

解决方案


JSON.net 具有在MaxDepth一定程度上去实现的属性。

请注意,这将在一定程度上帮助您。它不会识别相同的对象循环依赖,它只会在反序列化的第二级停止。

对于相反的事情(序列化),您可以在序列化时使用 json.net limit maxdepth来扩展JsonTextWriter


推荐阅读