Question

From the given DataContract I want to display just one XML node for Benefits. Since, at one time only one of the 3 DataMembers Houses, Cars and Shares will be not null.

public class WebAPIModel 
{
    [DataMember(Name = "Benefits")]
    public List<House> Houses { get; set; }
    [DataMember(Name = "Benefits")]
    public List<Car> Cars { get; set; }
    [DataMember(Name = "Benefits")]
    public List<Share> Shares { get; set; }     
}

(Obviously currently this doesn't work)

How can I make the resultant XML to display just one node Benefits?

I tried something like ...

    // Since only one property is not null at one time 
    // I thought EmitDefaultValue will do the trick .. but it doesn't
    [DataMember(Name = "Benefits", EmitDefaultValue = false)]
Was it helpful?

Solution

If it is about serialization, EmitDefaultValue = false should be enough.

For display purposes:

Create a new property called "Benefits", mark it as non-data member, implement getter.

It may have to be of a generic type, common ancestor for Car, Share, etc. As another option, you might define a new type and generate its instances on the fly when this new property is accessed.

If this approach with new property works for you, also consider implementing it in an extension class, existing in client application only, to reduce server-side clutter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top