Consider the following Student
defintion:
public class Student
{
public Guid Id {get; set;}
public String FirstName {get; set;}
public String LastName { get; set; }
}
Using C# serialization attributes, how can you apply two different serialization configurations?
When the object is passed to the DataContractSerializer
, the user could specify "idOnly" (partial) or "full" serialization.
I have a two runtime use cases:
- Only serialize the Guid
- Full serialization of the Object.
OK, delete the answer for
XmlSerializer
because you're usingDataContractSerializer
.One way you can accomplish this with
DataContractSerializer
is by use of surrogates. A surrogate basically is a replacement class that you swap in for one of your "real" classes while serializing, deserializing, and creating schemas. You can use this trick to replace your fullStudent
class with a simpleStudentId
class depending (e.g.) upon the state of someThreadStatic
state variable indicating whether the full or partial student is to be serialized. (I useThreadStatic
in case you might have multiple threads serializing data in parallel.)Thus your
Student
class would become something like this:And then your global flag:
Next you must create a
IDataContractSurrogate
class telling theDataContractSerializer
what replacements to make. In this example you will conditionally replaceStudent
when only the Id is desired. Since you are only doing serialization, not deserialization or schema generation, most methods can remain unimplemented:And finally, here is an example of how it is used:
In this test case, xml1 is
and xml2 is
which is what you seek. Finally, note that, while my test case serializes
Student
as a top-level object, the replacement will occur if it is nested deep inside some class object graph.For another example, see here: http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/14/wcf-extensibility-serialization-surrogates.aspx
I don't know what kind of serialization are you talking about. But if you use the BinaryFormatter, the way to go is to make the Student class implement the ISerializable.
Then, you can do something like:
Where SomeCondition may use a static (or thread-static) variable or some information inside the StreamingContext.