代码之家  ›  专栏  ›  技术社区  ›  2oppin

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

  •  2
  • 2oppin  · 技术社区  · 8 年前

    我有一个模型

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

    在控制器中,我有

    /**
     * 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为对象,给定数组

    在…vendor/jms/metadata/src/metadata/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方法中,我添加了额外的类型转换来接收对象,而不是assoc数组:

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

    有没有更干净的解决方案,而不添加自定义原则序列化?

    但愿如此 …vendor/jms/metadata/src/metadata/PropertyMetadata.php:51 有

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

    但它是

    return $this->reflection->getValue($obj); // :(
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   2oppin    8 年前

    我的问题在于使用@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指出我使事情复杂化:)