dahomey-technologies/Dahomey.Cbor

[Question] Possible to automatically not serialize empty Enumerables and properties which are null?

Closed this issue · 3 comments

Is it possible to not serialize Enumerables if they contain zero items? And the same for properties/fields, which have the value null?

Instead of: ...ups": [{"metaData": {}, "par... it should be ...ups": [{"par...

Yes, you just have to add a method
bool ShouldSerialize[PropertyName]() to the class and implement the condition to serialize or not the property or field.

In your case the method name would be ShouldSerializeMetadata

Even if I use this:

public ImmutableDictionary<string, string> MetaData { get; protected set; }
public bool ShouldSerializeMetaData() => false;

in my class, it still gets serialized

Fixed it. The problem was that this behavior is defined in DefaultObjectMappingConvention, but I am using my own IObjectMappingConvention. Thanks!