Is is possible in Symfony Serializer
to deserialize an array of objects in a property? I have a Boss
class with the $Npc = []
property tha
Yes, you can deserialize the array but you need to provide on the second parameter the object as well as the information that it is in fact an array. You can do this like this:
use Symfony\Component\Serializer\Serializer;
class Boss {
private $Npc = [];
/**
* @return Npc[]
*/
public function getNpcs(): array
{
return $serializer->deserialize($this->npcs, 'Acme\Npc[]', 'json');
}
}
You can find more information about this in the documentation on handling arrays
I have struggled with this many hours without getting a result. Every time i added an adder function, the objectnormalizer wanted to invoke this function but got an error something like "The field xyz should be of type xyz[], array given".
This is cause i forgot to add the ArrayDenormalizer
to the normalizer pool of the serializer. After adding this, everything worked fine.
Hope this is helpful for somebody.
I found a way to do this :). I installed the Symfony PropertyAccess package through Composer. With this package, you can add adders, removers and hassers. This way Symfony Serializer will automaticly fill the array with the correct objects. Example:
private $npcs = [];
public function addNpc(Npc $npc): void
{
$this->npcs[] = $npc;
}
public function hasNpcs(): bool
{
return count($this->npcs) > 0
}
etc.
This way you can use the ObjectNormalizer with:
$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
Edit: At least since v3.4 you have to create a remover method as well. Otherwise it just won't work (no error or warning).