@@ -671,6 +671,73 @@ you indicate that you're expecting an array instead of a single object.
671
671
$data = ...; // The serialized data from the previous example
672
672
$persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');
673
673
674
+ Recursive Denormalization and Type Safety
675
+ -----------------------------------------
676
+
677
+ The Serializer Component can use the :doc: `PropertyInfo Component </components/property_info >` to denormalize
678
+ complex types (objects). The type of the class's property will be guessed using the provided
679
+ extractor and used to recursively denormalize the inner data.
680
+
681
+ When using the Symfony Standard Edition, all normalizers are automatically configured to use registered extractors.
682
+ When using the component standalone, an implementation of :class: `Symfony\\ Component\\ PropertyInfo\\ PropertyTypeExtractorInterface `,
683
+ (usually an instance of :class: `Symfony\\ Component\\ PropertyInfo\\ PropertyInfoExtractor `) must be passed as the 4th
684
+ parameter of the normalizer::
685
+
686
+ use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
687
+ use Symfony\Component\Serializer\Serializer;
688
+ use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
689
+
690
+ namespace Acme;
691
+
692
+ class ObjectOuter
693
+ {
694
+ private $inner;
695
+ private $date;
696
+
697
+ public function getInner()
698
+ {
699
+ return $this->inner;
700
+ }
701
+
702
+ public function setInner(ObjectInner $inner)
703
+ {
704
+ $this->inner = $inner;
705
+ }
706
+
707
+ public function setDate(\DateTimeInterface $date)
708
+ {
709
+ $this->date = $date;
710
+ }
711
+
712
+ public function getDate()
713
+ {
714
+ return $this->date;
715
+ }
716
+ }
717
+
718
+ class ObjectInner
719
+ {
720
+ public $foo;
721
+ public $bar;
722
+ }
723
+
724
+ $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); //
725
+ $serializer = new Serializer(array(new DateTimeNormalizer(), $normalizer));
726
+
727
+ $obj = $serializer->denormalize(
728
+ array('inner' => array('foo' => 'foo', 'bar' => 'bar'), 'date' => '1988/01/21'),
729
+ 'Acme\ObjectOuter'
730
+ );
731
+
732
+ dump($obj->getInner()->foo); // 'foo'
733
+ dump($obj->getInner()->bar); // 'bar'
734
+ dump($obj->getDate()->format('Y-m-d')); // '1988-01-21'
735
+
736
+ When a ``PropertyTypeExtractor `` is available, the normalizer will also check that the data to denormalize
737
+ matches the type of the property (even for primitive types). For instance, if a ``string `` is provided but
738
+ the type of the property is ``int ``, a :class: `Symfony\\ Component\\ Serializer\\ Exception\\ UnexpectedValueException `
739
+ will be thrown.
740
+
674
741
.. seealso ::
675
742
676
743
A popular alternative to the Symfony Serializer Component is the third-party
0 commit comments