Jil序列化器忽略null属性

Jil序列化器忽略null属性

本文介绍了Jil序列化器忽略null属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在防止Jil序列化为null的属性的属性?

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

在Newtonsoft中是

In Newtonsoft it is :

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

推荐答案

对于整个对象, Options 是您想要的(许多不同的Option配置是预先计算的,类似于 Options.ExcludeNulls 也可以).

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

例如

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仅遵守 [DataMember] 上的 Name 选项.我想兑现 EmitDefaultValue 并不是最困难的事情,但是没人能打开问题.

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.

这篇关于Jil序列化器忽略null属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:41