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

Commitd611e77

Browse files
committed
featuresymfony#3701 [Serializer] add documentation for serializer callbacks (cordoval)
This PR was submitted for the master branch but it was merged into the 2.3 branch instead (closessymfony#3701).Discussion----------[Serializer] add documentation for serializer callbacksrelatedsymfony/symfony#10229| Q | A || --- | --- || Doc fix? | no || New docs? | yes || Applies to | 2.3+ || Fixed tickets | self 👶 || License | CC-ASA 3.0 Unported | Sent using [Gush](https://github.com/gushphp/gush)Commits-------b865b40 add comma madness and lowercasing Wefe2029 plug new revisioneabdbd0 add serializer set callback documentation
2 parents80c645c +a06ad9a commitd611e77

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎components/serializer.rst

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,37 @@ 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 Properties with Object Instances
185+
-------------------------------------------------------------
186+
187+
When serializing, you can set a callback to format a specific object property::
188+
189+
use Acme\Person;
190+
use Symfony\Component\Serializer\Encoder\JsonEncoder;
191+
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
192+
use Symfony\Component\Serializer\Serializer;
193+
194+
$encoder = new JsonEncoder();
195+
$normalizer = new GetSetMethodNormalizer();
196+
197+
$callback = function ($dateTime) {
198+
return $dateTime instanceof \DateTime
199+
? $dateTime->format(\DateTime::ISO8601)
200+
: '';
201+
}
202+
203+
$normalizer->setCallbacks(array('createdAt' => $callback));
204+
205+
$serializer = new Serializer(array($normalizer), array($encoder));
206+
207+
$person = new Person();
208+
$person->setName('cordoval');
209+
$person->setAge(34);
210+
$person->setCreatedAt(new \DateTime('now'));
211+
212+
$serializer->serialize($person, 'json');
213+
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
214+
184215
JMSSerializer
185216
-------------
186217

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp