Search code examples
symfonydoctrine-ormjmsserializerbundle

How to disable automatic casting of object properties?


I am using JMS serializer bundle to serialize and deserialize data within restful api. I have the following scenario:

Entity:

/**
 * Settings
 *
 * @ORM\Table(name="user_settings")
 * @ORM\Entity
 *
 * @JMS\ExclusionPolicy("none")
 * @JMS\AccessType("public_method")
 */
class Settings
{
    /**
     * @var boolean
     *
     * @ORM\Column(name="search", type="boolean")
     *
     * @JMS\Groups({"get", "update"})
     */
    private $search;
}

I have configured JMS to use Doctrine object constructor.

When I make a POST and deserialise the data into the Settings object, it works, but in a scenario like this:

{"id":5, "search":"string"}

It converts the string "string" into a boolean automatically. I believe it has something to do with doctrine. If I modify the ORM column annotation to type="string", the casting doesn't happen, which is what I want, but I want to keep type="boolean".

With the current situation, I cannot validate the object and say that "string" is not a valid value, because it is casted to boolean before I can do any validation on the object.

If you need further explanation, please let me know, and I would really appreciate your help.


Solution

  • I have found a solution for this.

    However, I didn't find any configuration possibilities for the bundle itself, but it was possible to override the following parameter:

    <parameter key="jms_serializer.json_deserialization_visitor.class">MyBundle\CoreBundle\Serializer\JsonDeserializationVisitor</parameter>
    

    The default GenericDeserializationVisitor was using the methods like visitBoolean(), and casting boolean types to boolean, which was my case.