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?
The ObjectNormalizer has an option to disable type enforcement when denormalizing which you can pass via the context parameter.
# ...
$myObj = $serializer->deserialize(
$body,
MyObj::class,
'json',
['disable_type_enforcement' => true]
);
# ...
Since you are using a type hint in your setter, php will try to convert the given value to int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With