Jil serializer ignore null properties

2019-07-09 01:41发布

问题:

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

In Newtonsoft it is :

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

回答1:

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.