6

当尝试序列化使用特征的模型时,JMSSerializer 不会序列化该特征包含的属性。我正在使用 yaml 来配置序列化程序,但它似乎不起作用。

trait IdentityTrait
{

    protected $id;

    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    public function getId()
    {
        return $this->id;
    }
}

class OurClass {
   use IdentityTrait;

   protected $test;

   public function getTest() {
       $this->test;
   }
}

使用了JMSSerializerBundle,下面的yaml位于Resources/config/serializer/Model.Traits.IdentityTrait.yml

MyProject\Component\Core\Model\Traits\IdentityTrait:
    exclusion_policy: NONE
    properties:
    id:
        expose: true

并且OurClass配置位于Resources/config/serializer/Model.OurClass.yml

 MyProject\Component\Core\Model\OurClass:
     exclusion_policy: NONE
     properties:
         test:
             expose: true

一些代码已被忽略以专注于问题

4

2 回答 2

1

自PHP 5.4.0开始引入 PHP 特征,最新的 JMSSerializer 代码支持PHP 5.3.2。注意"require": {"php": ">=5.3.2",查看代码,此功能不受支持(尚)。这个问题与JMSSerializer github上的这个问题非常相关。

于 2014-11-15T18:45:40.167 回答
-1

可以使用 Trait 进行序列化:

<?php
namespace AppBundle\Entity;

use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\Type;


trait EntityDateTrait
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     * @Expose()
     * @Groups({"DeploymentListing", "DeploymentDetails"})
     * @Type("DateTime")
     */
    protected $createdAt;

    /**
     *
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     * @Expose()
     * @Groups({"DeploymentListing", "DeploymentDetails"})
     * @Type("DateTime")
     */
    protected $updatedAt;


    /**
     * @ORM\PrePersist()
     *
     * Set createdAt.
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

    /**
     * Get createdAt.
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @ORM\PreUpdate()
     *
     * Set updatedAt.
     *
     * @return Campaign
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new \DateTime();
    }

    /**
     * Get updatedAt.
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

不要忘记在字段上添加@type。

于 2019-07-02T14:32:30.583 回答