Search code examples
phpsymfonyjmsserializerbundlesymfony-2.8jms-serializer

JMS Serializer not serializing child classes


I have problem with JMS serializer. When I use groups, JMS not serializes my child classes, but when i dont use groups all is okay. What i doing wrongly?

    $context = SerializationContext::create()->enableMaxDepthChecks();
    $context->setGroups(['clientapi']);

    $contextWithoutGroup = SerializationContext::create()->enableMaxDepthChecks();

    /** @var Serializer $serializer */
    $serializer = $this->container->get('jms_serializer');
    $dataClientApi = $serializer->serialize($documentBundle->getFolderDocumentsForClientApi(
        $this->getUserFromParam($params), $folder, $categories, $tags
    ), 'json', $context);

    $dataWithout = $serializer->serialize($documentBundle->getFolderDocumentsForClientApi(
        $this->getUserFromParam($params), $folder, $categories, $tags
    ), 'json', $$contextWithoutGroup);

Give:

$dataClientApi = '{"0":{"author":{}}}';
$dataWithout = '{"0":{"author":{id: 2}}}';

And that are my classes. Parent:

/**
 * Document
 *
 * @ORM\Table(name="documents")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\DocumentRepository")
 * @ORM\EntityListeners({"DocumentListener"})
 * @JMS\ExclusionPolicy("all")
 * @JMS\AccessorOrder("custom", custom = {"id", "folderId", "title"})
 */
class Document implements ResourceInterface
{

    use Traits\SortableTrait;
    use Traits\TimestampableTrait;

    /**
     * @var integer
     *
     * @ORM\Column(type="integer", name="id")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @JMS\Groups({"clientapi"})
     * @JMS\Expose()
     */
    protected $id;

    /**
     * @var \AppBundle\Entity\Author
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Author")
     * @ORM\JoinColumn(name="author_id", nullable=true, referencedColumnName="id")
     * @JMS\Groups({"clientapi"})
     * @JMS\MaxDepth(3)
     * @JMS\Expose()
     */
    protected $author;

And child class:

/**
 * Author
 *
 * @ORM\Entity
 * @ORM\Table(name="author")
 * @Gedmo\Uploadable(pathMethod="getDirPath", allowOverwrite=false, filenameGenerator="SHA1", appendNumber=true)
 * @JMS\ExclusionPolicy("none")
 * @JMS\AccessorOrder("custom", custom = {"id"})
 */
class Author implements ResourceInterface, FileInterface
{
    const DIR_PATH = 'web/system/authors';

    use Traits\FileTrait;
    use Traits\TimestampableTrait;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @JMS\Groups({"clientapi"})
     * @JMS\Expose()
     */
    protected $id;

Solution

  • You should check if you not mix serializer defined by annotations and that with .yml files. That often make hardly to debug troubles.