diff --git a/components/serializer.rst b/components/serializer.rst index e45dc61f74c..f84718286b6 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -181,6 +181,37 @@ method on the normalizer definition:: As a final result, the deserializer uses the ``first_name`` attribute as if it were ``firstName`` and uses the ``getFirstName`` and ``setFirstName`` methods. +Using Callbacks to Serialize Properties with Object Instances +------------------------------------------------------------- + +When serializing, you can set a callback to format a specific object property:: + + use Acme\Person; + use Symfony\Component\Serializer\Encoder\JsonEncoder; + use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; + use Symfony\Component\Serializer\Serializer; + + $encoder = new JsonEncoder(); + $normalizer = new GetSetMethodNormalizer(); + + $callback = function ($dateTime) { + return $dateTime instanceof \DateTime + ? $dateTime->format(\DateTime::ISO8601) + : ''; + } + + $normalizer->setCallbacks(array('createdAt' => $callback)); + + $serializer = new Serializer(array($normalizer), array($encoder)); + + $person = new Person(); + $person->setName('cordoval'); + $person->setAge(34); + $person->setCreatedAt(new \DateTime('now')); + + $serializer->serialize($person, 'json'); + // Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"} + JMSSerializer -------------