-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathserializer.rst
More file actions
2723 lines (2047 loc) · 97.9 KB
/
serializer.rst
File metadata and controls
2723 lines (2047 loc) · 97.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
How to Use the Serializer
=========================
Symfony provides a serializer to transform data structures from one format
to PHP objects and the other way around.
This is most commonly used when building an API or communicating with third
party APIs. The serializer can transform an incoming JSON request payload
to a PHP object that is consumed by your application. Then, when generating
the response, you can use the serializer to transform the PHP objects back
to a JSON response.
It can also be used to, for instance, load CSV configuration data as PHP
objects, or even to transform between formats (e.g. YAML to XML).
.. _activating_the_serializer:
Installation
------------
In applications using :ref:`Symfony Flex <symfony-flex>`, run this command to
install the serializer :ref:`Symfony pack <symfony-packs>` before using it:
.. code-block:: terminal
$ composer require symfony/serializer-pack
.. note::
The serializer pack also installs some commonly used optional
dependencies of the Serializer component. When using this component
outside the Symfony framework, you might want to start with the
``symfony/serializer`` package and install optional dependencies if you
need them.
.. seealso::
A popular alternative to the Symfony Serializer component is the third-party
library, `JMS serializer`_.
Serializing an Object
---------------------
For this example, assume the following class exists in your project::
// src/Model/Person.php
namespace App\Model;
class Person
{
public function __construct(
private int $age,
private string $name,
private bool $sportsperson
) {
}
public function getAge(): int
{
return $this->age;
}
public function getName(): string
{
return $this->name;
}
public function isSportsperson(): bool
{
return $this->sportsperson;
}
}
If you want to transform objects of this type into a JSON structure (e.g.
to send them via an API response), get the ``serializer`` service by using
the :class:`Symfony\\Component\\Serializer\\SerializerInterface` parameter type:
.. configuration-block::
.. code-block:: php-symfony
// src/Controller/PersonController.php
namespace App\Controller;
use App\Model\Person;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
class PersonController extends AbstractController
{
public function index(SerializerInterface $serializer): Response
{
$person = new Person('Jane Doe', 39, false);
$jsonContent = $serializer->serialize($person, 'json');
// $jsonContent contains {"name":"Jane Doe","age":39,"sportsperson":false}
return JsonResponse::fromJsonString($jsonContent);
}
}
.. code-block:: php-standalone
use App\Model\Person;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
$person = new Person('Jane Done', 39, false);
$jsonContent = $serializer->serialize($person, 'json');
// $jsonContent contains {"name":"Jane Doe","age":39,"sportsperson":false}
The first parameter of the :method:`Symfony\\Component\\Serializer\\Serializer::serialize`
is the object to be serialized and the second is used to choose the proper
encoder (i.e. format), in this case the :class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder`.
.. tip::
When your controller class extends ``AbstractController`` (like in the
example above), you can simplify your controller by using the
:method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController::json`
method to create a JSON response from an object using the Serializer::
class PersonController extends AbstractController
{
public function index(): Response
{
$person = new Person('Jane Doe', 39, false);
// when the Serializer is not available, this will use json_encode()
return $this->json($person);
}
}
Using the Serializer in Twig Templates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can also serialize objects in any Twig template using the ``serialize``
filter:
.. code-block:: twig
{{ person|serialize(format = 'json') }}
See the :ref:`twig reference <reference-twig-filter-serialize>` for more
information.
Deserializing an Object
-----------------------
APIs often also need to convert a formatted request body (e.g. JSON) to a
PHP object. This process is called *deserialization* (also known as "hydration"):
.. configuration-block::
.. code-block:: php-symfony
// src/Controller/PersonController.php
namespace App\Controller;
// ...
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Request;
class PersonController extends AbstractController
{
// ...
public function create(Request $request, SerializerInterface $serializer): Response
{
if ('json' !== $request->getContentTypeFormat()) {
throw new BadRequestException('Unsupported content format');
}
$jsonData = $request->getContent();
$person = $serializer->deserialize($jsonData, Person::class, 'json');
// ... do something with $person and return a response
}
}
.. code-block:: php-standalone
use App\Model\Person;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
// ...
$jsonData = ...; // fetch JSON from the request
$person = $serializer->deserialize($jsonData, Person::class, 'json');
In this case, :method:`Symfony\\Component\\Serializer\\Serializer::deserialize`
needs three parameters:
#. The data to be decoded
#. The name of the class this information will be decoded to
#. The name of the encoder used to convert the data to an array (i.e. the
input format)
When sending a request to this controller (e.g.
``{"first_name":"John Doe","age":54,"sportsperson":true}``), the serializer
will create a new instance of ``Person`` and sets the properties to the
values from the given JSON.
.. note::
By default, additional attributes that are not mapped to the
denormalized object will be ignored by the Serializer component. For
instance, if a request to the above controller contains ``{..., "city": "Paris"}``,
the ``city`` field will be ignored. You can also throw an exception in
these cases using the :ref:`serializer context <serializer-context>`
you'll learn about later.
.. seealso::
You can also deserialize data into an existing object instance (e.g.
when updating data). See :ref:`Deserializing in an Existing Object <serializer-populate-existing-object>`.
.. _serializer-process:
The Serialization Process: Normalizers and Encoders
---------------------------------------------------
The serializer uses a two-step process when (de)serializing objects:
.. raw:: html
<object data="_images/serializer/serializer_workflow.svg" type="image/svg+xml"
alt="A flow diagram showing how objects are serialized/deserialized. This is described in the subsequent paragraph."
></object>
In both directions, data is always first converted to an array. This splits
the process in two separate responsibilities:
Normalizers
These classes convert **objects** into **arrays** and vice versa. They
do the heavy lifting of finding out which class properties to
serialize, what value they hold and what name they should have.
Encoders
Encoders convert **arrays** into a specific **format** and the other
way around. Each encoder knows exactly how to parse and generate a
specific format, for instance JSON or XML.
Internally, the ``Serializer`` class uses a sorted list of normalizers and
one encoder for the specific format when (de)serializing an object.
There are several normalizers configured in the default ``serializer``
service. The most important normalizer is the
:class:`Symfony\\Component\\Serializer\\Normalizer\\ObjectNormalizer`. This
normalizer uses reflection and the :doc:`PropertyAccess component </components/property_access>`
to transform between any object and an array. You'll learn more about
:ref:`this and other normalizers <serializer-normalizers>` later.
The default serializer is also configured with some encoders, covering the
common formats used by HTTP applications:
* :class:`Symfony\\Component\\Serializer\\Encoder\\JsonEncoder`
* :class:`Symfony\\Component\\Serializer\\Encoder\\XmlEncoder`
* :class:`Symfony\\Component\\Serializer\\Encoder\\CsvEncoder`
* :class:`Symfony\\Component\\Serializer\\Encoder\\YamlEncoder`
Read more about these encoders and their configuration in
:doc:`/serializer/encoders`.
.. tip::
The `API Platform`_ project provides encoders for more advanced
formats:
* `JSON-LD`_ along with the `Hydra Core Vocabulary`_
* `OpenAPI`_ v2 (formerly Swagger) and v3
* `GraphQL`_
* `JSON:API`_
* `HAL`_
.. _serializer-context:
Serializer Context
~~~~~~~~~~~~~~~~~~
The serializer, and its normalizers and encoders, are configured through
the *serializer context*. This context can be configured in multiple
places:
* :ref:`Globally through the framework configuration <serializer-default-context>`
* :ref:`While serializing/deserializing <serializer-context-while-serializing-deserializing>`
* :ref:`For a specific property <serializer-using-context-builders>`
You can use all three options at the same time. When the same setting is
configured in multiple places, the latter in the list above will override
the previous one (e.g. the setting on a specific property overrides the one
configured globally).
.. _serializer-default-context:
Configure a Default Context
...........................
You can configure a default context in the framework configuration, for
instance to disallow extra fields while deserializing:
.. configuration-block::
.. code-block:: yaml
# config/packages/serializer.yaml
framework:
serializer:
default_context:
allow_extra_attributes: false
.. code-block:: xml
<!-- config/packages/serializer.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services
https://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:serializer>
<framework:default-context>
<framework:allow-extra-attributes>false</framework:allow-extra-attributes>
</framework:default-context>
</framework:serializer>
</framework:config>
</container>
.. code-block:: php
// config/packages/serializer.php
use Symfony\Config\FrameworkConfig;
return static function (FrameworkConfig $framework): void {
$framework->serializer()
->defaultContext([
'allow_extra_attributes' => false,
])
;
};
.. code-block:: php-standalone
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
// ...
$normalizers = [
new ObjectNormalizer(null, null, null, null, null, null, [
'allow_extra_attributes' => false,
]),
];
$serializer = new Serializer($normalizers, $encoders);
.. _serializer-context-while-serializing-deserializing:
Pass Context while Serializing/Deserializing
............................................
You can also configure the context for a single call to
``serialize()``/``deserialize()``. For instance, you can skip
properties with a ``null`` value only for one serialize call::
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
// ...
$serializer->serialize($person, 'json', [
AbstractObjectNormalizer::SKIP_NULL_VALUES => true
]);
// next calls to serialize() will NOT skip null values
.. _serializer-using-context-builders:
Using Context Builders
""""""""""""""""""""""
You can use "context builders" to help define the (de)serialization
context. Context builders are PHP objects that provide autocompletion,
validation, and documentation of context options::
use Symfony\Component\Serializer\Context\Normalizer\DateTimeNormalizerContextBuilder;
$contextBuilder = (new DateTimeNormalizerContextBuilder())
->withFormat('Y-m-d H:i:s');
$serializer->serialize($something, 'json', $contextBuilder->toArray());
Each normalizer/encoder has its related context builder. To create a more
complex (de)serialization context, you can chain them using the
``withContext()`` method::
use Symfony\Component\Serializer\Context\Encoder\CsvEncoderContextBuilder;
use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder;
$initialContext = [
'custom_key' => 'custom_value',
];
$contextBuilder = (new ObjectNormalizerContextBuilder())
->withContext($initialContext)
->withGroups(['group1', 'group2']);
$contextBuilder = (new CsvEncoderContextBuilder())
->withContext($contextBuilder)
->withDelimiter(';');
$serializer->serialize($something, 'csv', $contextBuilder->toArray());
.. seealso::
You can also :doc:`create your context builders </serializer/custom_context_builders>`
to have autocompletion, validation, and documentation for your custom
context values.
Configure Context on a Specific Property
........................................
At last, you can also configure context values on a specific object
property. For instance, to configure the datetime format:
.. configuration-block::
.. code-block:: php-attributes
// src/Model/Person.php
// ...
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
class Person
{
#[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
public \DateTimeImmutable $createdAt;
// ...
}
.. code-block:: yaml
# config/serializer/person.yaml
App\Model\Person:
attributes:
createdAt:
contexts:
- context: { datetime_format: 'Y-m-d' }
.. code-block:: xml
<!-- config/serializer/person.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
<class name="App\Model\Person">
<attribute name="createdAt">
<context>
<entry name="datetime_format">Y-m-d</entry>
</context>
</attribute>
</class>
</serializer>
.. note::
When using YAML or XML, the mapping files must be placed in one of
these locations:
* All ``*.yaml`` and ``*.xml`` files in the ``config/serializer/``
directory.
* The ``serialization.yaml`` or ``serialization.xml`` file in the
``Resources/config/`` directory of a bundle;
* All ``*.yaml`` and ``*.xml`` files in the ``Resources/config/serialization/``
directory of a bundle.
.. tip::
Symfony provides a JSON schema for serializer mapping files that enables
autocompletion and validation in IDEs like PhpStorm. Add the following
``$schema`` key at the beginning of your YAML files to enable this feature:
.. code-block:: yaml
# config/serializer/person.yaml
'$schema': https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.json
App\Model\Person:
attributes:
# your IDE will now provide autocompletion here...
.. versionadded:: 7.4
The JSON schema for serializer mapping files was introduced in Symfony 7.4.
You can also specify a context specific to normalization or denormalization:
.. configuration-block::
.. code-block:: php-attributes
// src/Model/Person.php
// ...
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
class Person
{
#[Context(
normalizationContext: [DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'],
denormalizationContext: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339],
)]
public \DateTimeImmutable $createdAt;
// ...
}
.. code-block:: yaml
# config/serializer/person.yaml
App\Model\Person:
attributes:
createdAt:
contexts:
- normalization_context: { datetime_format: 'Y-m-d' }
denormalization_context: { datetime_format: !php/const \DateTime::RFC3339 }
.. code-block:: xml
<!-- config/serializer/person.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
<class name="App\Model\Person">
<attribute name="createdAt">
<normalization-context>
<entry name="datetime_format">Y-m-d</entry>
</normalization-context>
<denormalization-context>
<entry name="datetime_format">Y-m-d\TH:i:sP</entry>
</denormalization-context>
</attribute>
</class>
</serializer>
.. _serializer-context-group:
You can also restrict the usage of a context to some
:ref:`groups <serializer-groups-attribute>`:
.. configuration-block::
.. code-block:: php-attributes
// src/Model/Person.php
// ...
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
class Person
{
#[Groups(['extended'])]
#[Context([DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339])]
#[Context(
context: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339_EXTENDED],
groups: ['extended'],
)]
public \DateTimeImmutable $createdAt;
// ...
}
.. code-block:: yaml
# config/serializer/person.yaml
App\Model\Person:
attributes:
createdAt:
groups: [extended]
contexts:
- context: { datetime_format: !php/const \DateTime::RFC3339 }
- context: { datetime_format: !php/const \DateTime::RFC3339_EXTENDED }
groups: [extended]
.. code-block:: xml
<!-- config/serializer/person.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
<class name="App\Model\Person">
<attribute name="createdAt">
<group>extended</group>
<context>
<entry name="datetime_format">Y-m-d\TH:i:sP</entry>
</context>
<context>
<entry name="datetime_format">Y-m-d\TH:i:s.vP</entry>
<group>extended</group>
</context>
</attribute>
</class>
</serializer>
The attribute can be repeated as much as needed on a single property.
Context without group is always applied first. Then context for the
matching groups are merged in the provided order.
If you repeat the same context in multiple properties, consider using the
``#[Context]`` attribute on your class to apply that context configuration to
all the properties of the class::
namespace App\Model;
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
#[Context([DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339])]
#[Context(
context: [DateTimeNormalizer::FORMAT_KEY => \DateTime::RFC3339_EXTENDED],
groups: ['extended'],
)]
class Person
{
// ...
}
Serializing JSON Using Streams
------------------------------
Symfony can encode PHP data structures to JSON streams and decode JSON streams
back into PHP data structures.
To do this, it relies on the :doc:`JsonStreamer component </serializer/streaming_json>`,
which is designed for high efficiency and can process large JSON data incrementally,
without needing to load the entire content into memory.
When deciding between the Serializer component and the JsonStreamer component,
consider the following:
* **Serializer Component**: Best suited for use cases that require flexibility,
such as dynamically manipulating object structures using normalizers and
denormalizers, or handling complex objects with multiple serialization
formats. It also supports output formats beyond JSON (including your own
custom ones).
* **JsonStreamer Component**: Best suited for simple objects and scenarios that
demand high performance and low memory usage. It's particularly effective
for processing very large JSON datasets or when streaming JSON in real-time
without loading the entire dataset into memory.
The choice depends on your specific use case. The JsonStreamer component is
tailored for performance and memory efficiency, whereas the Serializer
component provides greater flexibility and broader format support.
Read more about :doc:`streaming JSON </serializer/streaming_json>`.
Serializing to or from PHP Arrays
---------------------------------
The default :class:`Symfony\\Component\\Serializer\\Serializer` can also be
used to only perform one step of the :ref:`two step serialization process <serializer-process>`
by using the respective interface:
.. configuration-block::
.. code-block:: php-symfony
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
// ...
class PersonController extends AbstractController
{
public function index(DenormalizerInterface&NormalizerInterface $serializer): Response
{
$person = new Person('Jane Doe', 39, false);
// use normalize() to convert a PHP object to an array
$personArray = $serializer->normalize($person, 'json');
// ...and denormalize() to convert an array back to a PHP object
$personCopy = $serializer->denormalize($personArray, Person::class);
// ...
}
public function json(DecoderInterface&EncoderInterface $serializer): Response
{
$data = ['name' => 'Jane Doe'];
// use encode() to transform PHP arrays into another format
$json = $serializer->encode($data, 'json');
// ...and decode() to transform any format to just PHP arrays (instead of objects)
$data = $serializer->decode('{"name":"Charlie Doe"}', 'json');
// $data contains ['name' => 'Charlie Doe']
}
}
.. code-block:: php-standalone
use App\Model\Person;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
// use normalize() to convert a PHP object to an array
$personArray = $serializer->normalize($person, 'json');
// ...and denormalize() to convert an array back to a PHP object
$personCopy = $serializer->denormalize($personArray, Person::class);
$data = ['name' => 'Jane Doe'];
// use encode() to transform PHP arrays into another format
$json = $serializer->encode($data, 'json');
// ...and decode() to transform any format to just PHP arrays (instead of objects)
$data = $serializer->decode('{"name":"Charlie Doe"}', 'json');
// $data contains ['name' => 'Charlie Doe']
.. _serializer_ignoring-attributes:
Ignoring Properties
-------------------
The ``ObjectNormalizer`` normalizes *all* properties of an object and all
methods starting with ``get*()``, ``has*()``, ``is*()`` and ``can*()``.
Some properties or methods should never be serialized. You can exclude
them using the ``#[Ignore]`` attribute:
.. configuration-block::
.. code-block:: php-attributes
// src/Model/Person.php
namespace App\Model;
use Symfony\Component\Serializer\Attribute\Ignore;
class Person
{
// ...
#[Ignore]
public function isPotentiallySpamUser(): bool
{
// ...
}
}
.. code-block:: yaml
App\Model\Person:
attributes:
potentiallySpamUser:
ignore: true
.. code-block:: xml
<?xml version="1.0" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
<class name="App\Model\Person">
<attribute name="potentiallySpamUser" ignore="true"/>
</class>
</serializer>
The ``potentiallySpamUser`` property will now never be serialized:
.. configuration-block::
.. code-block:: php-symfony
use App\Model\Person;
// ...
$person = new Person('Jane Doe', 32, false);
$json = $serializer->serialize($person, 'json');
// $json contains {"name":"Jane Doe","age":32,"sportsperson":false}
$person1 = $serializer->deserialize(
'{"name":"Jane Doe","age":32,"sportsperson":false","potentiallySpamUser":false}',
Person::class,
'json'
);
// the "potentiallySpamUser" value is ignored
.. code-block:: php-standalone
use App\Model\Person;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
// ...
// you need to pass a class metadata factory with a loader to the
// ObjectNormalizer when reading mapping information like Ignore or Groups.
// E.g. when using PHP attributes:
$classMetadataFactory = new ClassMetadataFactory(new AttributeLoader());
$normalizers = [new ObjectNormalizer($classMetadataFactory)];
$serializer = new Serializer($normalizers, $encoders);
$person = new Person('Jane Doe', 32, false);
$json = $serializer->serialize($person, 'json');
// $json contains {"name":"Jane Doe","age":32,"sportsperson":false}
$person1 = $serializer->deserialize(
'{"name":"Jane Doe","age":32,"sportsperson":false","potentiallySpamUser":false}',
Person::class,
'json'
);
// the "potentiallySpamUser" value is ignored
Ignoring Attributes Using the Context
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can also pass an array of attribute names to ignore at runtime using
the ``ignored_attributes`` context options::
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
// ...
$person = new Person('Jane Doe', 32, false);
$json = $serializer->serialize($person, 'json',
[
AbstractNormalizer::IGNORED_ATTRIBUTES => ['age'],
]);
// $json contains {"name":"Jane Doe","sportsperson":false}
However, this can quickly become unmaintainable if used excessively. See
the next section about *serialization groups* for a better solution.
.. _serializer-groups-attribute:
Selecting Specific Properties
-----------------------------
Instead of excluding a property or method in all situations, you might need
to exclude some properties in one place, but serialize them in another.
Groups are a handy way to achieve this.
You can add the ``#[Groups]`` attribute to your class:
.. configuration-block::
.. code-block:: php-attributes
// src/Model/Person.php
namespace App\Model;
use Symfony\Component\Serializer\Attribute\Groups;
class Person
{
#[Groups(["admin-view"])]
private int $age;
#[Groups(["public-view"])]
private string $name;
#[Groups(["public-view"])]
private bool $sportsperson;
private string $email;
// ...
}
.. code-block:: yaml
# config/serializer/person.yaml
App\Model\Person:
attributes:
age:
groups: ['admin-view']
name:
groups: ['public-view']
sportsperson:
groups: ['public-view']
# email has no groups defined
.. code-block:: xml
<!-- config/serializer/person.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
>
<class name="App\Model\Person">
<attribute name="age">
<group>admin-view</group>
</attribute>
<attribute name="name">
<group>public-view</group>
</attribute>
<attribute name="sportsperson">
<group>public-view</group>
</attribute>
<!-- email has no groups defined -->
</class>
</serializer>
You can now choose which groups to use when serializing::
$json = $serializer->serialize(
$person,
'json',
['groups' => 'public-view']
);
// $json contains {"name":"Jane Doe","sportsperson":false}
// you can also pass an array of groups
$json = $serializer->serialize(
$person,
'json',
['groups' => ['public-view', 'admin-view']]
);
// $json contains {"name":"Jane Doe","age":32,"sportsperson":false}
// or use the special "*" value to serialize all properties
// (including those without any groups)
$json = $serializer->serialize(
$person,
'json',
['groups' => '*']
);
// $json contains {"name":"Jane Doe","age":32,"sportsperson":false,"email":"jane.doe@exemple.com"}
Using the Serialization Context
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At last, you can also use the ``attributes`` context option to select
properties at runtime::
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
// ...
$json = $serializer->serialize($person, 'json', [
AbstractNormalizer::ATTRIBUTES => ['name', 'company' => ['name']]
]);
// $json contains {"name":"Dunglas","company":{"name":"Les-Tilleuls.coop"}}
Only attributes that are :ref:`not ignored <serializer_ignoring-attributes>`
are available. If serialization groups are set, only attributes allowed by
those groups can be used.
.. _serializer-handling-arrays:
Handling Arrays
---------------
The serializer is capable of handling arrays of objects. Serializing arrays
works just like serializing a single object::
use App\Model\Person;
// ...
$person1 = new Person('Jane Doe', 39, false);
$person2 = new Person('John Smith', 52, true);
$persons = [$person1, $person2];
$jsonContent = $serializer->serialize($persons, 'json');