Custom JSON serializers for a Symfony 3 entity
Asked Answered
B

1

6

I have a Symfony 3.2 entity using Doctrine's Translatable extension.

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;

    /* [...] */
}

I know how to use the basic way to serialize this entity in JSON (I use friendsofsymfony/rest-bundle for the serialization of my REST API), but I would like to serialize it in a custom way like this...

{
    "description": {
        "fr": "description en français",
        "en": "english description",
    }
}
Biddick answered 7/7, 2017 at 10:50 Comment(2)
This might help: https://mcmap.net/q/1919243/-how-to-create-a-custom-normilizer-for-serializing-json-in-symfony-5/10543130Clostridium
What serializer are you using? Symfony Serializer, JMS Serializer, other one?Sp
N
0

try this :

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;

    /* [...] */
}
Nineteenth answered 8/7, 2017 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.