Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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<MoodressBundlePosteBundleEntityPoste> does not exist

How I do deserialize :

$lastPosts = $serializer->deserialize($data['data'], 'array<MoodressBundlePosteBundleEntityPoste>', '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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
713 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

namespace MoodressBundlePosteBundleResponse;

use JMSSerializerAnnotationType;

class PosteResponse
{
    /**
     * @Type("integer")
     */
    private $total;

    /**
     * @Type("array<MoodressBundlePosteBundleEntityPoste>")
     */
    private $data;

    //getters here
}

and deserialize your response to that class:

$response = $serializer->deserialize(
    $json,
    'MoodressBundlePosteBundleResponsePosteResponse',
    '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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...