In web api, I'm serializing a class that contains properties that are IEnumerable
and I only want the properties to be serialized if they are not empty collections.
[DataMember(EmitDefaultValue = false)]
does not work because the properties are not null since they are initialized in the constructor.
[DataContract]
public class Linkable : ILinkable {
[DataMember(EmitDefaultValue = false)]
public IList<ILink> links { get; set; }
[DataMember(EmitDefaultValue = false)]
public IList<ILink> linkTemplates { get; set; }
public Linkable() {
links = new List<ILink>();
linkTemplates = new List<ILink>();
}
}
Is there a way to do this with an Attribute
? If not, how can I accomplish this?
Can you just leave the collections null until you need to add something to them? For example:
public class Linkable {
public IList<ILink> links { get; set; }
public void AddLink(ILink link) {
if (links == null) {
links = new List<ILink>();
}
links.Add(link);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.