Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit dce3cc2

Browse filesBrowse files
cordovalweaverryan
authored andcommitted
add serializer set callback documentation
1 parent 80c645c commit dce3cc2
Copy full SHA for dce3cc2

File tree

Expand file treeCollapse file tree

1 file changed

+27
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+27
-0
lines changed

‎components/serializer.rst

Copy file name to clipboardExpand all lines: components/serializer.rst
+27Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,33 @@ method on the normalizer definition::
181181
As a final result, the deserializer uses the ``first_name`` attribute as if
182182
it were ``firstName`` and uses the ``getFirstName`` and ``setFirstName`` methods.
183183

184+
Using Callbacks to Serialize DateTime Objects
185+
---------------------------------------------
186+
187+
If you have DateTime type fields or need special formatting needs when deserializing
188+
a particular property from your object you can use the callbacks feature::
189+
190+
$encoder = new JsonEncoder();
191+
$normalizer = new GetSetMethodNormalizer();
192+
193+
$callback = function ($dateTime) {
194+
return $dateTime instanceof \DateTime
195+
? $dateTime->format(\DateTime::ISO8601)
196+
: '';
197+
}
198+
199+
$normalizer->setCallbacks(array('createdAt' => $callback));
200+
201+
$serializer = new Serializer(array($normalizer), array($encoder));
202+
203+
$person = new Acme\Person();
204+
$person->setName('cordoval');
205+
$person->setAge(34);
206+
$person->setCreatedAt(new \DateTime('now'));
207+
208+
$serializer->serialize($person, 'json');
209+
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
210+
184211
JMSSerializer
185212
-------------
186213

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.