Symfony-将json反序列化为实体数组 [英] Symfony - Deserialize json to an array of entities
问题描述
我有一个通过调用get API收到的json对象.我进行此调用以接收对象列表.这是一个帖子列表...所以我有一系列的Post Objects.
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.
这里是输出:
{
"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"
}
]
}
我想反序列化数据部分... 问题是Symfony中的序列化器给我一个错误...
I would like to deserialize the data part... The problem is that the Serializer in Symfony gives me an error ...
我遇到的错误:
Class array<Moodress\Bundle\PosteBundle\Entity\Poste> does not exist
我如何反序列化:
$lastPosts = $serializer->deserialize($data['data'], 'array<Moodress\Bundle\PosteBundle\Entity\Poste>', 'json');
我如何反序列化数据数组...要有一个Postes数组.我想给出我的观点.twig一个数组Poste ...当我反序列化时我确实精确了类型...所以我找不到问题所在...
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...
谢谢.
推荐答案
错误非常明显.您的字符串与任何现有的类都不匹配.
The error is pretty clear. Your string does not match any existant class.
$person = $serializer->deserialize($data,'Acme\Person','xml');
您的情况应该更像是:
$person = $serializer->deserialize($data['data'],'Moodress\Bundle\PosteBundle\Entity\Poste','json');
更新:
好吧.
首先,您的json文件似乎无效(使用 http://jsonlint.com/进行测试它).小心点.
First, your json file does not seem to be valid (use http://jsonlint.com/ to test it). Be careful of that.
第二,您将必须使用以下数组来获取json作为数组
Second, you will have to fetch your json as an array with
$data = json_decode($yourJsonFile, true);
然后您可以使用
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. */
}
这篇关于Symfony-将json反序列化为实体数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!