Refactored serialization code into a serialize interface.