Search code examples
apisymfonyserializationdeserializationjson-deserialization

Failed to denormalize attribute "date" value for class


I am trying to save by API an object given by the Front in React JS

So I have this object testing in Insomnia:

{
"rate": 1.59,
"correction":"2 ui nOVORAPID",
"date": "2020-11-26",
"time": "7:30"}

I don't understand why i have the error

Failed to denormalize attribute "date" value for class "App\Entity\Bloodsugar": Expected argument of type "string", "object" given at property path "date".

My controller:

        $user = $this->getUser();

        $jsonReceived = $request->getContent();

        $json = json_decode($jsonReceived);

        $newBloodsugar = $serializer->deserialize($jsonReceived, BloodSugar::class, 'json');

...

I guess that Symfony does not recognize the date format "Y-m-d", how can I do so ?


Solution

  • I guess your BloodSugar class has invalid setter or property type. Normally symfony-serializer normalize dates to Datetime, while your entity is expecting string. Try to change it to DatetimeInterface, smth like this:

    class BloodSugar {
        //..
        private ?DatetimeInterface $date;
        //..
        public function setDate(DatetimeInterface $date){
            $this->date = $date;
            return $this;
        }
        //..
    }