I need to deserialize a JSON file (which is a table from an old database) into a "Training" entity object.
The problem I am encountering is an error :
Failed to denormalize attribute "start_at" value for class "App\Entity\Training": Expected argument of type "DateTimeImmutable", "string" given at property path "start_at".
The serializer is called in the construct: (What is commented is a test without using the SerializerInterface)
public function __construct(
string $projectDir,
SerializerInterface $serializer,
ManagerRegistry $doctrine
) {
$this->projectDir = $projectDir;
$this->serializer = $serializer;
$this->doctrine = $doctrine;
// $encoders = [new JsonEncoder()];
// $normalizers = [new ObjectNormalizer(null, null, null, new ReflectionExtractor()), new DateTimeNormalizer()];
// $this->serializer = new Serializer($normalizers, $encoders);
}
JSON file:
{
"id": "13",
"type_id": "3",
"title": "Technical training",
"description": "the description",
"start_at": "2018-05-14 09:00:00",
"end_at": "2018-05-18 17:00:00",
"pj": "file.pdf",
"places_dispos": "2",
"created_at": "2018-01-15 10:20:59",
"updated_at": "2019-04-29 18:01:55"
}
My function:
public function readJsonFile(string $fileName, string $tableName)
{
$file = $this->projectDir . '/var/json-database/extranet_table_' . $fileName . '.json';
$fileString = file_get_contents($file);
$fileObj = json_decode($fileString, true);
return $this->convertJsonToObject($fileObj['data'], $tableName);
}
private function convertJsonToObject(array $arrayData, string $tableName)
{
$arrayTableObj = [];
foreach ($arrayData as $data) {
$data['id'] = intval($data['id']);
//Boolean
if (isset($data['active'])) {
($data['active'] === '1') ? $data['active'] = true : $data['active'] = false;
}
if (isset($data['updatable'])) {
($data['updatable'] === '1') ? $data['updatable'] = true : $data['updatable'] = false;
}
$dataJson = json_encode($data);
// $dataObj = $this->serializer->deserialize($dataJson, "App\Entity\\". $tableName, 'json');
$dataObj = $this->serializer->deserialize($dataJson, "App\Entity\\". $tableName, 'json', [
DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s',
]);
$dataObj->setId($data['id']);
$arrayTableObj[] = $dataObj;
}
return $this->importInDatabase($arrayTableObj);
}
In my Training entity:
#[ORM\Column(type: 'datetime_immutable')]
private $startAt;
#[ORM\Column(type: 'datetime_immutable')]
private $endAt;
I tried to transform the content of "start_at" into DateTimeImmutable or DateTime, it doesn't change anything except the error message (array given).
CodePudding user response:
I think I understood my mistake. The displayed error did not help me. The problem I think, is that the property "start_at" in base is different from my entity "startAt".
If I rename "start_at" in the JSON to "startAt" it works. I don't delete the question, if it can help people not to make the same mistake as me.