3

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

In Newtonsoft it is :

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Guy Assaf
  • 888
  • 9
  • 24

1 Answers1

3

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.

Kevin Montrose
  • 22,191
  • 9
  • 88
  • 137
  • Does Jil recognize the "ShouldSerialize" method or somthing should be add ? – Guy Assaf Feb 09 '16 at 06:58
  • @guyAssaf Conditional Serialization in .NET is adding an instance method returning `bool` with the name `ShouldSerializeXXX()` for property `XXX`. Jil respects that. – Kevin Montrose Feb 09 '16 at 14:48
  • @KevinMontrose: How can I do it, When I want Ignore all null values globally. Like I do in JSON.net `GlobalConfiguration.Configuration .Formatters .JsonFormatter .SerializerSettings .NullValueHandling = NullValueHandling.Ignore;` in gloabl.asax.cs file – Amit Kumar May 12 '16 at 14:09
  • @AmitKumar you can call [`JSON.SetDefaultOptions(Options)`](https://github.com/kevin-montrose/Jil/blob/75ffc895d0483fccb60a45d2bdcbaf4c78604496/Jil/JSON.cs#L29) to set global configurations. These can still be overridden by passing an `Options` object at the callsite. – Kevin Montrose May 12 '16 at 14:21