views:

261

answers:

2

I'm converting some of my classes to use DataContractSerialization so that I can include Linq Entities in the output. A sort of theoretical question popped into my head while I was in the process, and while I'm betting the answer is "No" I figured I'd pose the question anyway.

Is there a way to conditionally serialize an object? For instance if I'm serializing an Employee object with the intention to send information to a customer I might not want to include the address. On the other hand if I'm serializing it to use in a web service for the site that manages that employee I might need that info.

Another possibility would be serializing certain members based on whether they were the base object being serialized or not. So if I have a Ticket class which contains a Location, and the Location contains a list of Contacts I probably wouldn't want that contacts list if I were serializing the Ticket. But if I were trying to work with the Location itself, it might be good to have.

So any thoughts on that?

A: 

I haven't used WCF yet, but I know with standard Serialization in .Net (attribute based), I could have an OnSerializing and an OnDeserialized method on a class; Perhaps WCF offers something similiar? Within those methods, you could conditionally remove data (although keep in mind this means your object has changed, which is a pretty nasty side effect of serialization).

Example:

public class Employee
{
    public Address HomeAddress { get; set; }

    [OnSerializing]
    private void RemoveAddress(StreamingContext context)
    {
        if (1 == 1) // replace with your condition
            HomeAddress = null;
    }

    [OnDeserialized]
    private void PutAddressBack(StreamingContext context)
    {
        if (1 == 1)
            HomeAddress = LoadHomeAddressFromBackingStore();
    }
}
Chris Shaffer
A: 

I recommend against directly returning LINQ to SQL or ADO.NET Entity Framework objects from a web service. Unfortunately, this serializes implementation-specifics. For instance, base class fields are also serialized, as are back links.

John Saunders