Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)]
like image 395
Guy Assaf Avatar asked Dec 03 '25 15:12

Guy Assaf


1 Answers

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.

like image 77
Kevin Montrose Avatar answered Dec 06 '25 04:12

Kevin Montrose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!