phpjsonsymfonydeserializationjmsserializerbundle

Symfony - Deserialize json to an array of entities


I have a json object that I received by making a get API call. I make this call to receive a list of objects. It's a list of post... So I have an array of Post Objects.

Here the output :

{
    "total":2,
    "data":[
      {
        "id":2,
        "user":{
          "id":1,
          "username":"sandro.tchikovani"             
        },
        "description":"cool",
        "nb_comments":0,
        "nb_likes":0,
        "date_creation":"2014-04-13T20:07:34-0700"
      },
      {
        "id":1,
        "user":{
           "id":1,
           "username":"sandro.tchikovani",
         },
        "description":"Premier pooooste #lol",
        "nb_comments":0,
        "nb_likes":0,
        "date_creation":"2014-04-13T15:15:35-0700"
      }
    ]
 }

I would like to deserialize the data part... The problem is that the Serializer in Symfony gives me an error ...

The error that I have :

Class array<Moodress\Bundle\PosteBundle\Entity\Poste> does not exist

How I do deserialize :

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

How can I deserialze the data array... To have an array of Postes. I want to give to my view .twig an array Poste... I did precise the type when I deserialize... So I can't find what is the problem...

Thanks.


Solution

  • The error is pretty clear. Your string does not match any existant class.

    The example in official documentation says:

    $person = $serializer->deserialize($data,'Acme\Person','xml');
    

    In your case it should be more like:

    $person = $serializer->deserialize($data['data'],'Moodress\Bundle\PosteBundle\Entity\Poste','json');
    

    Update:

    Ok then.

    First, your json file does not seem to be valid (use http://jsonlint.com/ to test it). Be careful of that.

    Second, you will have to fetch your json as an array with

    $data = json_decode($yourJsonFile, true);
    

    and then you can access to each 'data' array with

    foreach($data['data'] as $result)
    {
        /* Here you can hydrate your object manually like:
        $person = new Person();
        $person->setId($user['id']);
        $person->setDescription($user['description']);
    
        Or you can use a denormalizer. */
    }