Symfony 3 实体的自定义 JSON 序列化程序

Dam*_*bin 6 symfony doctrine-orm doctrine-extensions symfony-3.2

我有一个使用Doctrine's Translatable extension的 Symfony 3.2 实体。

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Media
 *
 * @ORM\Table(name="medias")
 * @Gedmo\TranslationEntity(class="AppBundle\Entity\Translation\MediaTranslation")
 */
class Media implements Translatable
{
    /* [...] */
    
    /**
     * @var string|null
     *
     * @ORM\Column(type="text", nullable=true)
     * @Gedmo\Translatable
     * @Groups({"single_media"})
     */
    private $description;

    /* [...] */
}
Run Code Online (Sandbox Code Playgroud)

我知道如何使用基本方法在 JSON 中序列化这个实体(我friendsofsymfony/rest-bundle用于 REST API 的序列化),但我想以这样的自定义方式序列化它......

{
    "description": {
        "fr": "description en français",
        "en": "english description",
    }
}
Run Code Online (Sandbox Code Playgroud)

wal*_*ili 0

尝试这个 :

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Media
 *
 * @ORM\Table(name="medias")
 * @Gedmo\TranslationEntity(class="AppBundle\Entity\Translation\MediaTranslation")
 */
class Media implements Translatable, \Serializable
{
    /* [...] */

    /**
     * @var string|null
     *
     * @ORM\Column(type="text", nullable=true)
     * @Gedmo\Translatable
     * @Groups({"single_media"})
     */
    private $description;

    /* [...] */
}
Run Code Online (Sandbox Code Playgroud)