使用Doctrine和JMSSerializer注释序列化对象数组


serialize array of objects using Doctrine and JMSSerializer annotations

我有一个模型

    /**
     * @ORM'Table(name="polygon")
     * @ORM'Entity(repositoryClass="MyBundle'Repository'PolygonRepository")
     * @JMS'ExclusionPolicy("none")
     */
    class Polygon {
         /**
          * @var string
          *
          * @ORM'Column(name="polygon", type="json_array")
          * @JMS'Type("array<MyBundle'Model'Point>")
          */
          private $points;
          /***/
    }

DB存储像文本"[{"x":1、"y":1}…]"

在控制器中我有

/**
 * Matches /polygon exactly
 *
 * @Route("/", name="polygon_list")
 * @Method("GET")
 *
 * @Rest'Get("/")
 *
 */
public function listAction()
{
    return $this->container->get('doctrine.orm.entity_manager')
        ->getRepository('MyBundle:Polygon')
        ->findAll();
}

所以我得到ReflectionProperty::getValue()期望参数1为给定的对象数组

…供应商/jms/元数据/src/元数据/PropertyMetadata.php: 51

如果只得到结果,可以使用虚属性

来解决。
/**
 * @JMS'Exclude
 */
private $points;
/**
 * @JMS'VirtualProperty
 * @JMS'Type("array<MyBundle'Model'Point>")
 * @JMS'SerializedName("points")
 * @JMS'Groups({"common"})
 *
 * @return array
 */
public function getMyPoints() {
    return [new Point(), new Point()]
}

但是我需要从POST接收这个点作为JSON,所以到目前为止我发现的唯一方法是类似的教条自定义类型https://github.com/sonata-project/sonata-doctrine-extensions

唯一不同的是,在convertToPHPValue方法中,我添加了额外的类型转换来接收对象,而不是关联数组:

// pass my [{"x":1, "y":1} ...]
public function convertToPHPValue($value, AbstractPlatform $platform)
    {
       return array_map(function($a){ return (object)$a;}, json_decode($value));
    }

是否有一个更干净的解决方案,不添加自定义原则序列化?

if only this…供应商/jms/元数据/src/元数据/PropertyMetadata.php: 51有

return $this->reflection->getValue((object)$obj);

return $this->reflection->getValue($obj); // :(

我的问题是在使用@JMS'Type

    class Polygon {
         /**
          * @ORM'Column(name="polygon", type="json_array")
          */
          private $points;
          public function getPoints() { return $this->points;}
          public function setPoints($points) {
               $this->points = $points;
               return $this;
          }
          /***/
    }

工作得很好,谢谢@Matteo指出我使事情复杂化了:)