gpt4 book ai didi

symfony - JMS序列化器如何手动处理序列化?

转载 作者:行者123 更新时间:2023-12-04 20:09:31 26 4
gpt4 key购买 nike

我想使用 JMSSerializerBundle 手动反序列化 JSON。我在 HandlerCallback 上遇到了一些麻烦。这是一个代码:

namespace Company\Bundle\Model;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\HandlerCallback;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\TypeParser;
use JMS\Serializer\Serializer;

class Blog
{
protected $blogName;

protected $blogUrl;

protected $blogCategory;
/**
* @Type("array<Company\Bundle\Model\Post>")
* @SerializedName("data")
*/
protected $posts;

/**
* @param mixed $posts
*/
public function setPosts($posts)
{
$this->posts = $posts;
}

/**
* @return mixed
*/
public function getPosts()
{
return $this->posts;
}

/**
* @HandlerCallback("json", direction = "deserialization")
*/
public function deserializeFromJson(JsonDeserializationVisitor $visitor, array $data, DeserializationContext $context)
{
$this->blogName = $data['data'][0]['blogName'];
$this->blogUrl = $data['data'][0]['blogUrl'];
$this->blogCategory = $data['data'][0]['blogCategory'];

$this->posts = ????;
}
}

我应该添加什么而不是???获取对象 Company\Bundle\Model\Post 的数组

最佳答案

也许是这样的:

/**
* @HandlerCallback("json", direction = "deserialization")
*/
public function deserializeFromJson(JsonDeserializationVisitor $visitor, array $data, DeserializationContext $context)
{
$this->blogName = $data['data'][0]['blogName'];
$this->blogUrl = $data['data'][0]['blogUrl'];
$this->blogCategory = $data['data'][0]['blogCategory'];

$this->posts = new ArrayCollection();
for ( $data['data'][0]['posts'] as $post_data ){
$this->posts->add(new Post($post_data));
// OR
$this->posts->add(Post::deserializeFromJson($post_data));
}
}

关于symfony - JMS序列化器如何手动处理序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20263299/

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