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

前端 未结 3 1235
心在旅途
心在旅途 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:43

    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

    0 讨论(0)
  • 2021-02-20 11:52

    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.

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题