@@ -769,6 +769,74 @@ you indicate that you're expecting an array instead of a single object.
769
769
$data = ...; // The serialized data from the previous example
770
770
$persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');
771
771
772
+ Recursive Denormalization and Type Safety
773
+ -----------------------------------------
774
+
775
+ The Serializer Component can use the :doc: `PropertyInfo Component </components/property_info >` to denormalize
776
+ complex types (objects). The type of the class' property will be guessed using the provided
777
+ extractor and used to recursively denormalize the inner data.
778
+
779
+ When using the Symfony Standard Edition, all normalizers are automatically configured to use the registered extractors.
780
+ When using the component standalone, an implementation of :class: `Symfony\\ Component\\ PropertyInfo\\ PropertyTypeExtractorInterface `,
781
+ (usually an instance of :class: `Symfony\\ Component\\ PropertyInfo\\ PropertyInfoExtractor `) must be passed as the 4th
782
+ parameter of the ``ObjectNormalizer ``::
783
+
784
+ use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
785
+ use Symfony\Component\Serializer\Serializer;
786
+ use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
787
+ use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
788
+
789
+ namespace Acme;
790
+
791
+ class ObjectOuter
792
+ {
793
+ private $inner;
794
+ private $date;
795
+
796
+ public function getInner()
797
+ {
798
+ return $this->inner;
799
+ }
800
+
801
+ public function setInner(ObjectInner $inner)
802
+ {
803
+ $this->inner = $inner;
804
+ }
805
+
806
+ public function setDate(\DateTimeInterface $date)
807
+ {
808
+ $this->date = $date;
809
+ }
810
+
811
+ public function getDate()
812
+ {
813
+ return $this->date;
814
+ }
815
+ }
816
+
817
+ class ObjectInner
818
+ {
819
+ public $foo;
820
+ public $bar;
821
+ }
822
+
823
+ $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); //
824
+ $serializer = new Serializer(array(new DateTimeNormalizer(), $normalizer));
825
+
826
+ $obj = $serializer->denormalize(
827
+ array('inner' => array('foo' => 'foo', 'bar' => 'bar'), 'date' => '1988/01/21'),
828
+ 'Acme\ObjectOuter'
829
+ );
830
+
831
+ dump($obj->getInner()->foo); // 'foo'
832
+ dump($obj->getInner()->bar); // 'bar'
833
+ dump($obj->getDate()->format('Y-m-d')); // '1988-01-21'
834
+
835
+ When a ``PropertyTypeExtractor `` is available, the normalizer will also check that the data to denormalize
836
+ matches the type of the property (even for primitive types). For instance, if a ``string `` is provided, but
837
+ the type of the property is ``int ``, an :class: `Symfony\\ Component\\ Serializer\\ Exception\\ UnexpectedValueException `
838
+ will be thrown.
839
+
772
840
Learn more
773
841
----------
774
842
0 commit comments