@@ -2033,6 +2033,70 @@ correct class for properties typed as ``InvoiceItemInterface``::
20332033 $invoiceLine = $serializer->deserialize($jsonString, InvoiceLine::class, 'json');
20342034 // $invoiceLine contains new InvoiceLine(new Product(...))
20352035
2036+ You can add a default type to avoid the need to add the type property
2037+ when deserializing:
2038+
2039+ .. configuration-block ::
2040+
2041+ .. code-block :: php-attributes
2042+
2043+ namespace App\Model;
2044+
2045+ use Symfony\Component\Serializer\Attribute\DiscriminatorMap;
2046+
2047+ #[DiscriminatorMap(
2048+ typeProperty: 'type',
2049+ mapping: [
2050+ 'product' => Product::class,
2051+ 'shipping' => Shipping::class,
2052+ ],
2053+ defaultType: 'product',
2054+ )]
2055+ interface InvoiceItemInterface
2056+ {
2057+ // ...
2058+ }
2059+
2060+ .. code-block :: yaml
2061+
2062+ App\Model\InvoiceItemInterface :
2063+ discriminator_map :
2064+ type_property : type
2065+ mapping :
2066+ product : ' App\Model\Product'
2067+ shipping : ' App\Model\Shipping'
2068+ default_type : product
2069+
2070+ .. code-block :: xml
2071+
2072+ <?xml version =" 1.0" encoding =" UTF-8" ?>
2073+ <serializer xmlns =" http://symfony.com/schema/dic/serializer-mapping"
2074+ xmlns : xsi =" http://www.w3.org/2001/XMLSchema-instance"
2075+ xsi : schemaLocation =" http://symfony.com/schema/dic/serializer-mapping
2076+ https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
2077+ >
2078+ <class name =" App\Model\InvoiceItemInterface" >
2079+ <discriminator-map type-property =" type" default-type =" product" >
2080+ <mapping type =" product" class =" App\Model\Product" />
2081+ <mapping type =" shipping" class =" App\Model\Shipping" />
2082+ </discriminator-map >
2083+ </class >
2084+ </serializer >
2085+
2086+ Now it deserializes like this:
2087+
2088+ .. configuration-block ::
2089+
2090+ .. code-block :: php
2091+
2092+ // $jsonString does NOT contain "type" in "invoiceItem"
2093+ $invoiceLine = $serializer->deserialize('{"invoiceItem":{...},...}', InvoiceLine::class, 'json');
2094+ // $invoiceLine contains new InvoiceLine(new Product(...))
2095+
2096+ .. versionadded :: 7.3
2097+
2098+ The ``defaultType `` parameter was added in Symfony 7.3.
2099+
20362100.. _serializer-unwrapping-denormalizer :
20372101
20382102Deserializing Input Partially (Unwrapping)
0 commit comments