The Light
The Light

Reputation: 27021

How to hide/exclude a list node with DataContractSerializer when it has no value?

How to hide a list node with DataContractSerializer when it has no value?

[DataContract(Namespace = "")]
    public class Order
    {
        [DataMember(EmitDefaultValue = false)]
        public string Name { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public List<OrderItem> OrderItems { get; set; }
}

If Name has no value, it will be hidden but if OrderItems has no value it will appear as <OrderItems />.

I'm using DataContractSerlializer.

Upvotes: 0

Views: 186

Answers (1)

Vandesh
Vandesh

Reputation: 6904

It should work. Unless you are doing -

yourObject.OrderItems = new List<OrderItem>();

in your code somewhere. For which, memory is allocated to the list and it has no longer the default value null! Rather, its an empty list of OrderItem

Hence, EmitDefaultValue won't work if you are initializing the list somewhere in your code before serialization and will add <OrderItems /> to your XML.

Upvotes: 1

Related Questions