title: Skip empty collections when serializing to JSON
body: <p>I am working on a C# project. The following is my JSON. I want to remove the  &quot;items&quot;:[] from it for &quot;Type&quot;:&quot;Product&quot; as it is causing problems on the UI. I tried to exclude the value while JSON is being created by using the following Item class as described at <a href="https://stackoverflow.com/questions/34304738/how-to-ignoring-fields-and-properties-conditionally-during-serialization-using-j">How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net?</a>. But it didn't work, not sure why. Alternatively, is there a way to remove it after the JSON is created?</p>
  <pre><code>  [
       {
        &quot;Type&quot;:&quot;Category&quot;,
        &quot;Order&quot;:1,
        &quot;id&quot;:&quot;24&quot;,
        &quot;text&quot;:&quot;abc&quot;,
        &quot;items&quot;:[
           {
              &quot;Type&quot;:&quot;Product&quot;,
              &quot;Order&quot;:0,
              &quot;id&quot;:1900,
              &quot;text&quot;:&quot;abc product&quot;,
              &quot;items&quot;:[
                 
              ]
           }
        ]
     },
     {
        &quot;Type&quot;:&quot;Category&quot;,
        &quot;Order&quot;:1,
        &quot;id&quot;:&quot;6&quot;,
        &quot;text&quot;:&quot;efg&quot;,
        &quot;items&quot;:[
           {
              &quot;Type&quot;:&quot;Product&quot;,
              &quot;Order&quot;:0,
              &quot;id&quot;:2446,
              &quot;text&quot;:&quot;efg Product&quot;,
              &quot;items&quot;:[
                 
              ]
           },
           {
              &quot;Type&quot;:&quot;Product&quot;,
              &quot;Order&quot;:0,
              &quot;id&quot;:2447,
              &quot;text&quot;:&quot;efg1 Product&quot;,
              &quot;items&quot;:[
                 
              ]
           }
        ]
     }
    ]
  </code></pre>
  <pre><code>    [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&lt;Item&gt; items { get; set; }
  
          public bool ShouldSerializeitems()
          {
              return this.Type != &quot;Product&quot;;
          }
  
          public Item()
          {
              items = new List&lt;Item&gt;();
          }
      }
  </code></pre>
  <pre><code>    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 = &quot;Product&quot;;
         Category.items.Add(product);
      }
  </code></pre>