Skip to content

Instantly share code, notes, and snippets.

@BenMorel
Created January 2, 2022 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenMorel/4a9b1b4444751695a031e3d7c4aa177a to your computer and use it in GitHub Desktop.
Save BenMorel/4a9b1b4444751695a031e3d7c4aa177a to your computer and use it in GitHub Desktop.
Symfony Serializer: deserializing JSON to DTO example
<?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