gpt4 book ai didi

php - Symfony - 将 json 反序列化为实体数组

转载 作者:IT王子 更新时间:2023-10-29 00:19:55 25 4
gpt4 key购买 nike

我有一个 json 对象,它是通过调用 get API 收到的。我进行此调用是为了接收对象列表。这是一个帖子列表...所以我有一个帖子对象数组。

这里输出:

{
"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 中的 Serializer 给我一个错误 ...

我遇到的错误:

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

我如何反序列化:

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

我怎样才能反序列化数据数组......要有一个帖子数组。我想给我的 View .twig 一个数组 Poste...我在反序列化时确实精确了类型...所以我找不到问题所在...

谢谢。

最佳答案

我认为这里最好的解决方案是创建新的 PosteResponse 类,如下所示:

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
}

并反序列化你对该类的响应:

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

这样就可以了,而且它不需要您手动解码和编码您的 json,这在我看来是荒谬的。

关于php - Symfony - 将 json 反序列化为实体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com