Search code examples
phpsymfonyserialization

How to serialize nested object in symfony


I have the next class

#[Assert\Cascade]
class PropertyPromotionDto
{
    public function __construct(
        private string $name,
        #[Assert\NotBlank(message: 'Не может быть пустым')]
        private int $value,

        #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i'])]
        private DateTimeImmutable $date,

        private NestedDto $nestedDto,

        /** @var NestedDto[] */
        private array $nestedDtos,

        private Phone $phone
    ) {
    }


    
class NestedDto
{
    public function __construct(
        #[Assert\NotBlank(message:"Не должен быть пустым")]
        private string $author,

        private int $age,
        private ?DateTimeImmutable $date = null,
        private ?Phone $phone,
    ){
    }
}

}

And i have the next json

       {
            "name":"Mane",
            "value":42,
            "nestedDto": {"author": "Jane", "age": 35, "date":"2023-09-12"},
            "nestedDtos": [
                {"author": "",  "age": 20, "date":"2023-09-12"},
                {"author": "Pane", "age": 22}
            ]
        }

When i try to deserialize it, i catch error. I tried use flex serializer and flex like below

$encoder = [new JsonEncoder()];
            $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
            $normalizer = [new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, $extractor)];
            $serializer = new \Symfony\Component\Serializer\Serializer($normalizer, $encoder);

            return $serializer->deserialize($data, $type, $format);

Failed asserting that exception of type "The type of the "date" attribute for class "App\Dto\NestedDto" must be one of "App\Dto\DateTimeImmutable" ("string" given)."

Help, please


Solution

  • It was my fault.

    Error says "must be one of App\Dto\DateTimeImmutable"

    I just forget import DateTimeImmutable in my class.