Symfony - Deserialize json to an array of entities Symfony - Deserialize json to an array of entities symfony symfony

Symfony - Deserialize json to an array of entities


I think the best solution here is to create new PosteResponse class, like this one:

namespace Moodress\Bundle\PosteBundle\Response;use JMS\Serializer\Annotation\Type;class PosteResponse{    /**     * @Type("integer")     */    private $total;    /**     * @Type("array<Moodress\Bundle\PosteBundle\Entity\Poste>")     */    private $data;    //getters here}

and deserialize your response to that class:

$response = $serializer->deserialize(    $json,    'Moodress\Bundle\PosteBundle\Response\PosteResponse',    'json');$posts = $response->getData();

That WILL do the trick, and it doesn't require you to decode and encode your json manually which is riddiculous in my opinion.


Since Symfony Serializer Component 2.8 to deserialize array of objects:

$persons = $serializer->deserialize($data, 'Acme\Person[]', 'json');

https://symfony.com/doc/master/components/serializer.html#handling-arrays


A less than ideal solution that I found was to first decode and then encode the json data again at the node that represents the data array. For example in your case:

$json = json_decode($json);$json = json_encode($json->data);$serializer->deserialize($json, 'array<Moodress\Bundle\PosteBundle\Entity\Poste>', 'json');

There must be a better solution than this but this seems more elegant than the above solution of de-serialising json.