symfony serializer type casting while deserializing

Let’s say I have a class

class MyObj
{
    /** @var int */
    private $myProp;

    public function getMyProp(): int
    {
        return $this->myProp;
    }

    public function setMyProp(int $myProp): self
    {
        $this->myProp = $myProp;

        return $this;
    }
}

If I want to deserialize following

$body = '{"myProp": "4"}';
$myObj = $serializer->deserialize($body, MyObj::class, 'json');

I obviously get an error saying that the types do not match.

The type of the “myProp” attribute for class “MyObj” must be one of “int” (“string” given).

Can I configure the serializer to typecast those values?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *