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

限于喜欢 提交于 2020-05-11 05:07:09

问题


Is is possible in Symfony Serializer to deserialize an array of objects in a property? I have a Boss class with the $Npc = [] property that needs to hold a array of Npc objects. I did see some examples in the documentation, but they do not state this feature. I have a json string with an array of NPC's For example:

class Boss {

    private $Npc = [];    

    /**
    * @return Npc[]
    */
    public function getNpcs(): array
    {
        return $this->npcs;
    }
}

I am using php7.1 and symfony/serializer version ^3.3.

Edit: I already tried PhpDocExtractor, but it would not let me install it. :(

Edit: This is a possible JSON value:

{
    "bossname": "Epic boss!",
    "npcs": [{
        "id": 24723,
        "name": "Selin Fireheart",
        "urlSlug": "selin-fireheart",
        "creatureDisplayId": 22642
    }]
}

回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/47273427/how-can-i-deserialize-an-array-of-objects-in-symfony-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!