Refactored the serialize method by extracting the serializeObject method to accommodate for reference and array fields.