Skip to content

Commit 9718c14

Browse files
derrabusxabbuh
authored andcommitted
[Serializer] Array Denormalization
1 parent 4fc429e commit 9718c14

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

components/serializer.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,55 @@ having unique identifiers::
573573
echo $serializer->serialize($org, 'json');
574574
// {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]}
575575

576+
Handling Arrays
577+
---------------
578+
579+
The Serializer component is capable of handling arrays of objects as well.
580+
Serializing arrays works just like serializing a single object::
581+
582+
use Acme\Person;
583+
584+
$person1 = new Person();
585+
$person1->setName('foo');
586+
$person1->setAge(99);
587+
$person1->setSportsman(false);
588+
589+
$person2 = new Person();
590+
$person2->setName('bar');
591+
$person2->setAge(33);
592+
$person2->setSportsman(true);
593+
594+
$persons = array($person1, $person2);
595+
$data = $serializer->serialize($persons, 'json');
596+
597+
// $data contains [{"name":"foo","age":99,"sportsman":false},{"name":"bar","age":33,"sportsman":true}]
598+
599+
.. versionadded:: 2.8
600+
The :class:`Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer`
601+
class was introduced in 2.8. Prior to Symfony 2.8, only the serialization of
602+
arrays is supported.
603+
604+
If you want to deserialize such a structure, you need to add the
605+
:class:`Symfony\\Component\\Serializer\\Normalizer\\ArrayDenormalizer`
606+
to the set of normalizers. By appending ``[]`` to the type parameter of the
607+
:method:`Symfony\\Component\\Serializer\\Serializer::deserialize` method,
608+
you indicate that you're expecting an array instead of a single object.
609+
610+
.. code-block:: php
611+
612+
use Symfony\Component\Serializer\Encoder\JsonEncoder;
613+
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
614+
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
615+
use Symfony\Component\Serializer\Serializer;
616+
617+
$serializer = new Serializer(
618+
array(new GetSetMethodNormalizer(), new ArrayDenormalizer()),
619+
array(new JsonEncoder())
620+
);
621+
622+
$data = ...; // The serialized data from the previous example
623+
$persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');
624+
576625
.. seealso::
577626

578627
A popular alternative to the Symfony Serializer Component is the third-party

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy