How to serialize object as its own property (array) using JMS Serializer EventSubscriberInterface (php, symfony)

one text

Solution:

Finally, I figured it out. I implemented SubscribingHandlerInterface

<?php

use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\JsonSerializationVisitor;
use Book;
use BooksCollection;

class BooksCollectionHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods(): array
    {
        return [
            [
                'type' => BooksCollection::class,
                'format' => 'json',
                'method' => 'serialize',
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
            ],
            [
                'type' => BooksCollection::class,
                'format' => 'json',
                'method' => 'deserialize',
                'direction' => GraphNavigatorInterface::DIRECTION_DESERIALIZATION,
            ]
        ];
    }

    public function serialize(
        JsonSerializationVisitor $visitor,
        BooksCollection $booksCollection,
        array $type,
        Context $context
    ) {
        return $visitor->visitArray($booksCollection->getBooks(), ['name' => 'array'], $context);
    }

    public function deserialize(
        JsonDeserializationVisitor $visitor,
        array $data,
        array $type,
        Context $context
    ): BooksCollection {
        $collection = [];

        foreach ($data as $book) {
            $collection[] =
                $visitor->getNavigator()->accept($book, ['name' => Book::class], $context);
        }

        return new BooksCollection(...$collection);
    }
}

service config:

    books_handler:
        class: BooksCollectionHandler
        tags:
            - { name: jms_serializer.subscribing_handler }

Source