Home Ask Login Register

Developers Planet

Your answer is one click away!

guy Assaf February 2016

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)]

Answers


Kevin Montrose February 2016

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.

Post Status

Asked in February 2016
Viewed 3,613 times
Voted 8
Answered 1 times

Search




Leave an answer


Quote of the day: live life