@@ -573,6 +573,55 @@ having unique identifiers::
573
573
echo $serializer->serialize($org, 'json');
574
574
// {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]}
575
575
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
+
576
625
.. seealso ::
577
626
578
627
A popular alternative to the Symfony Serializer Component is the third-party
0 commit comments