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

时间:2013-11-28 10:17:28

标签: symfony jms jmsserializerbundle

我想用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

的数组

2 个答案:

答案 0 :(得分:2)

也许是这样的:

/**
 * @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));
    }
}

答案 1 :(得分:2)

您实际上可以重复使用其他对象和本地注释。

/**
 * @HandlerCallback("json",  direction = "deserialization")
 */
public function deserializeFromJson(JsonDeserializationVisitor $visitor, array $data, DeserializationContext $context)
{
    $typeParser = new TypeParser();

    /** @var ClassMetadata $metadata */
    $metadata = $context->getMetadataFactory()->getMetadataForClass(self::class);
    $visitor->startVisitingObject($metadata, $this, $typeParser->parse(self::class), $context);

    $visitor->visitProperty($metadata->propertyMetadata['blogName'], $data['data'][0], $context);
    $visitor->visitProperty($metadata->propertyMetadata['blogUrl'], $data['data'][0], $context);
    $visitor->visitProperty($metadata->propertyMetadata['blogCategory'], $data['data'][0], $context);
    $visitor->visitProperty($metadata->propertyMetadata['posts'], $data['data'][0], $context);
}