I have an entity which contains a DateTimeInterface type field called completedAt, and I want to deserialize a JSON object to this entity object.
I tried DateTimeNormalizer and ObjectNormalizer, but they both gave me an error saying that I can't assign string/array to DateTime object.
For example, I have this entity,
class Task
{
private $id;
private $name;
/**
* @var DateTimeInterface
*/
private $completedAt;
}
and how I create the JSON object in my test using PHPUnit,
$rawData = json_encode([
'name' => 'test-task',
'completedAt' => Carbon::now()->toRfc3339String(),
// I tried some other formats here, such as datetime array, datetime string, etc.
]);
In my controller, I tried this (It's a test, not my real code):
public function update(Request $request, Task $task, SerializerInterface $serializer): Response
{
$task = new Task();
$task->setName('test');
$task->setCompletedAt(Carbon::now()->toDateTime());
$json = $serializer->serialize($task, 'json');
$serializer = new Serializer([new ObjectNormalizer(), new DateTimeNormalizer()], [new JsonEncoder()]); // array of needed normalizer
var_dump($serializer->deserialize($json, Task::class, 'json'));
}
The I got this error,
NotNormalizableValueException Expected argument of type "DateTimeInterface", "string" given at property path "completedAt".
How can I deserialize that JSON object by using multiple normalizers?