序列化为 JSON 时跳过空集合

Skip empty collections when serializing to JSON

我正在处理 C# 项目。以下是我的JSON。我想从中删除“类型”:“产品”的“项目”:[],因为它在 UI 上引起了问题。我试图通过使用 中所述的以下项目 class 创建 JSON 时排除该值。但它没有用,不知道为什么。或者,有没有办法在 JSON 创建后删除它?

  [
     {
      "Type":"Category",
      "Order":1,
      "id":"24",
      "text":"abc",
      "items":[
         {
            "Type":"Product",
            "Order":0,
            "id":1900,
            "text":"abc product",
            "items":[
               
            ]
         }
      ]
   },
   {
      "Type":"Category",
      "Order":1,
      "id":"6",
      "text":"efg",
      "items":[
         {
            "Type":"Product",
            "Order":0,
            "id":2446,
            "text":"efg Product",
            "items":[
               
            ]
         },
         {
            "Type":"Product",
            "Order":0,
            "id":2447,
            "text":"efg1 Product",
            "items":[
               
            ]
         }
      ]
   }
  ]
    [Serializable]
    public class Item
    {
        public String Type { get; set; }
        public int Order { get; set; }
        public int id { get; set; }
        public string text { get; set; }
        public IList<Item> items { get; set; }

        public bool ShouldSerializeitems()
        {
            return this.Type != "Product";
        }

        public Item()
        {
            items = new List<Item>();
        }
    }
    foreach (Products product in products)
    {
                            
       Item product = new Item();
       product.id = Convert.ToInt32(product.GetProductID());
       product.text = product.GetName();
       product.Order = product.GetProductSortOrder();
       product.Type = "Product";
       Category.items.Add(product);
    }

从 JSON 字符串 post 序列化中删除数据几乎总是错误的方法。您应该在序列化期间始终处理它。

此外,您很可能应该检查 items 是否为空集合:

[Serializable]
public class Item
{
    public String Type { get; set; }
    public int Order { get; set; }
    public int id { get; set; }
    public string text { get; set; }
    public IList<Item> items { get; set; }

    public bool ShouldSerializeitems()
    {
        return items.Any();
    }

    public Item()
    {
        items = new List<Item>();
    }
}

这正确输出:

[
  {
    "Type": "Category",
    "Order": 1,
    "id": 24,
    "text": "abc",
    "items": [
      {
        "Type": "Product",
        "Order": 0,
        "id": 1900,
        "text": "abc product"
      }
    ]
  },
  {
    "Type": "Category",
    "Order": 1,
    "id": 6,
    "text": "efg",
    "items": [
      {
        "Type": "Product",
        "Order": 0,
        "id": 2446,
        "text": "efg Product"
      },
      {
        "Type": "Product",
        "Order": 0,
        "id": 2447,
        "text": "efg1 Product"
      }
    ]
  }
]