Symfony Serialize Entity with Datetime / Deserialize fails

Viewed 285

Im trying to save an Entity as a json file. The entity class also includes a datetime field:

class Ear
{
...
    /**
     * @ORM\Column(type="date")
     */
    private $date;
...
}

Then I create a new Ear:

$earLine = new Ear();
$earLine->setDate(new \DateTime());

Now I simply would think I can normalize and serialize this object:

$encoders = [new JsonEncoder()];
$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);

$json = $serializer->serialize($earLine, 'json');

which works fine. The json looks like this:

{
  "id": null,
  "date": "2021-05-31T00:00:00+02:00",
  ...
}

However upon trying to deserialize, it fails to denormalize the datetime.

$encoders = [new JsonEncoder()];
$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);

dd($serializer->deserialize($json, Ear::class, 'json'));

with the error Failed to denormalize attribute "date" value for class "App\Entity\Ear": Expected argument of type "DateTimeInterface", "string" given at property path "date".

I read the docs up and down and search stackoverflow. But it fails for not apparent reason, at least not for me.

Using Symfony 5.3.

0 Answers
Related