Doctrine entity to Json using GetSetMethodNormalizer return fatal error

后端 未结 2 1150
没有蜡笔的小新
没有蜡笔的小新 2021-01-11 09:27

I am using Doctrine 2 and Zend framework since a few days. I am generating my entities across yaml files. Now I met an issue to convert my entities Doctrine into Json format

相关标签:
2条回答
  • 2021-01-11 10:15

    I solved the same problem by writing my own GetSetNormalizer my class. Defined static variable in a class for branching

    class LimitedRecursiveGetSetMethodNormalizer extends GetSetMethodNormalizer
    { 
    public static $limit=2;
    /**
     * {@inheritdoc}
     */
    public function normalize($object, $format = null)
    {
        $reflectionObject = new \ReflectionObject($object);
        $reflectionMethods = $reflectionObject->getMethods(\ReflectionMethod::IS_PUBLIC);
    
        $attributes = array();
        foreach ($reflectionMethods as $method) {
            if ($this->isGetMethod($method)) {
                $attributeName = strtolower(substr($method->name, 3));
                $attributeValue = $method->invoke($object);
                if (null !== $attributeValue && !is_scalar($attributeValue) && LimitedRecursiveGetSetMethodNormalizer::$limit>0) {
                    LimitedRecursiveGetSetMethodNormalizer::$limit--;
                    $attributeValue = $this->serializer->normalize($attributeValue, $format);
                    LimitedRecursiveGetSetMethodNormalizer::$limit++;
                }
    
                $attributes[$attributeName] = $attributeValue;
            }
        }
    
        return $attributes;
    }
    
    /**
     * Checks if a method's name is get.* and can be called without parameters.
     *
     * @param ReflectionMethod $method the method to check
     * @return Boolean whether the method is a getter.
     */
    private function isGetMethod(\ReflectionMethod $method)
    {
        return (
            0 === strpos($method->name, 'get') &&
                3 < strlen($method->name) &&
                0 === $method->getNumberOfRequiredParameters()
        );
      } 
     }
    

    And usage

        LimitedRecursiveGetSetMethodNormalizer::$limit=3;
        $serializer = new Serializer(array(new LimitedRecursiveGetSetMethodNormalizer()), array('json' => new
        JsonEncoder()));
        $response =new Response($serializer->serialize($YOUR_OBJECT,'json'));
    
    0 讨论(0)
  • 2021-01-11 10:22

    JMSSerializerBundle seems to handle circular references fine.

    0 讨论(0)
提交回复
热议问题