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

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

提交回复
热议问题