'How to normalize a nested object with Symfony Serializer in Doctrine?
I'm using Symfony 6 and the Symfony Serializer. To deserialize JSON to PHP objects I'm using this function.
function deserialize(string $data, string $class, mixed $entity): mixed
{
$encoders = [new JsonEncoder()];
$extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
$normalizers = [new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, $extractor)];
$serializer = new Serializer($normalizers, $encoders);
return $serializer->deserialize(
$data, $class, 'json', [AbstractNormalizer::OBJECT_TO_POPULATE => $entity]
);
}
The problem with this is: When the following JSON is deserialized, the ID is set on the object (to 1), but is not retrieved by Doctrine:
{
"id": 1,
"name": "John Doe"
}
Persisting this results in duplicate data. The ID is ignored and a new object is created and persisted; The ID of the new object becomes 2. This could be fixed by retrieving the object beforehand and deserializing into this object. Unfortunately this cannot be done with nested objects like the one below.
{
"id": 1,
"guest": {
"id": 1,
"name": "John Doe"
}
}
So my question is, is there a way to deserialize (nested) objects and let them be tracked by doctrine?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
