Movatterモバイル変換


[0]ホーム

URL:


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

Sign up
Appearance settings

Commitdce3cc2

Browse files
cordovalweaverryan
authored andcommitted
add serializer set callback documentation
1 parent80c645c commitdce3cc2

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

‎components/serializer.rst‎

Lines 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)

[8]ページ先頭

©2009-2025 Movatter.jp