How can I deserialize an array of objects in Symfony Serializer?

前端 未结 3 1289
心在旅途
心在旅途 2021-02-20 11:29

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

3条回答
  •  一生所求
    2021-02-20 11:58

    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).

提交回复
热议问题