Outils pour utilisateurs

Outils du site


pele_mele:stack_exchange:stackoverflow-35478874

How to choose the driver to serialize/deserialize with jmsserializer

I have an object which I serialize using annotations. It works fine.

If I am using yaml configuration, it works fine also.

My problem is I want to use both in different context. Lets say that in controller one, I want to use the annotation configuration and in controller two, I want to use the yaml configuration. I want to do that because I need to have different field names in those outputs.

  • I tried to override the serializer with a new instance using only the annotation.
  • I change jmsserializer service configuration to not use specific drivers. It worked but I cannot choose which one to activate dynamically.
  • I tried to select the driver in the container but I couldn't make it work.

Is this possible? Am I missing something?

I don't see how you can achieve this.

But if you to want expose a property differently, you can create different views of your object by using an exclusion strategy.

Example :

/**
 * @JMS\ExclusionPolicy("all")
 * @ORM\Entity
 */
class FooBar
{    
    /**
     * @ORM\Column(type="string")
     * @JMS\Groups({"foo"})
     */
    protected $name; // output 'name'
 
    /**
     * @ORM\Column(type="string")
     * @JMS\SerializedName("foo_bar_name")
     * @JMS\Accessor(getter="getName", setter="setName")
     * @JMS\Groups({"bar"})
     */
    protected $fooName; // output 'foo_bar_name'
 
    // ...
 
    public function setName($name)
    {
        $this->address = $name;
 
        return $this;
    }
 
    public function getName()
    {
        return $this->name;
    }
}

Like this, the property can be serialised in two different names :

use JMS\Serializer\SerializationContext;
 
$serializer->serialize(new FooBar(), 'json', SerializationContext::create()->setGroups(array('foo')));
 
//will output $name as 'name'
 
$serializer->serialize(new FooBar(), 'json', SerializationContext::create()->setGroups(array('bar')));
 
//will output $fooName as 'foo_bar_name'

Note the @JMS\SerializedName is not mandatory, you can use it for custom names.

See more at the Exclusion strategies part of the documentation.

Hope this could be an alternative for you.

pele_mele/stack_exchange/stackoverflow-35478874.txt · Dernière modification : 2020/11/18 07:01 de alexis