Created
January 2, 2022 22:50
-
-
Save BenMorel/4a9b1b4444751695a031e3d7c4aa177a to your computer and use it in GitHub Desktop.
Symfony Serializer: deserializing JSON to DTO example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
use Symfony\Component\PropertyInfo\Extractor\ConstructorExtractor; | |
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; | |
use Symfony\Component\PropertyInfo\PropertyInfoExtractor; | |
use Symfony\Component\Serializer\Encoder\JsonEncoder; | |
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; | |
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; | |
use Symfony\Component\Serializer\Serializer; | |
class UserDTO { | |
/** | |
* @param AddressDTO[] $addressBook | |
*/ | |
public function __construct( | |
public string $name, | |
public int $age, | |
public ?AddressDTO $billingAddress, | |
public ?AddressDTO $shippingAddress, | |
public array $addressBook, | |
) { | |
} | |
} | |
class AddressDTO { | |
public function __construct( | |
public string $street, | |
public string $city, | |
) { | |
} | |
} | |
function deserialize(string $json, string $className): object | |
{ | |
$phpDocExtractor = new PhpDocExtractor(); | |
$typeExtractor = new PropertyInfoExtractor( | |
typeExtractors: [ | |
new ConstructorExtractor([$phpDocExtractor]), | |
$phpDocExtractor, | |
], | |
); | |
$normalizers = [ | |
new ObjectNormalizer(propertyTypeExtractor: $typeExtractor), | |
new ArrayDenormalizer(), | |
]; | |
$encoders = [ | |
new JsonEncoder(), | |
]; | |
$serializer = new Serializer($normalizers, $encoders); | |
return $serializer->deserialize($json, $className, 'json'); | |
} | |
$json = ' | |
{ | |
"name": "John", | |
"age": 25, | |
"billingAddress": { | |
"street": "Rue Paradis", | |
"city": "Marseille" | |
}, | |
"shippingAddress": null, | |
"addressBook": [ | |
{ | |
"street": "Rue Paradis", | |
"city": "Marseille" | |
} | |
] | |
} | |
'; | |
dd(deserialize($json, UserDTO::class)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment