Refactor serialization to share code.