Search code examples
c#.netserializationjsonserializerjil

Jil serializer ignore null properties


Is there an attribute to prevent Jil from serializing properties that are null ?

In Newtonsoft it is :

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

Solution

  • For the whole object, the excludeNulls parameter on Options is what you want (many different Options configurations are pre-calced, anything like Options.ExcludeNulls also works).

    You can control serialization of a single property with Conditional Serialization. (I forgot about this option in my original answer).

    For example

    class ExampleClass
    {
        public string DontSerializeIfNull {get;set;}
        public string AlwaysSerialize {get;set;}
    
        public bool ShouldSerializeDontSerializeIfNull()
        {
            return DontSerializeIfNull != null;
        }
    }
    
    JSON.Serialize(new ExampleClass { DontSerializeIfNull = null, AlwaysSerialize = null });
    // {"AlwaysSerialize":null}
    
    JSON.Serialize(new ExampleClass { DontSerializeIfNull = "foo", AlwaysSerialize = null });
    // {"AlwaysSerialize":null,"DontSerializeIfNull":"foo"}
    
    JSON.Serialize(new ExampleClass { DontSerializeIfNull = null, AlwaysSerialize = "bar" });
    // {"AlwaysSerialize":"bar"}
    
    JSON.Serialize(new ExampleClass { DontSerializeIfNull = "foo", AlwaysSerialize = "bar" });
    // {"AlwaysSerialize":"bar","DontSerializeIfNull":"foo"}
    

    Jil only respects the Name option on [DataMember]. I suppose honoring EmitDefaultValue wouldn't be the hardest thing, but nobody's ever opened an issue for it.