Improve serialization logic