Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

php - 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<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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...