Jil serializer ignore null properties

孤街醉人 提交于 2019-12-11 01:06:01

问题


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.



来源:https://stackoverflow.com/questions/35267108/jil-serializer-ignore-null-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!