Doctrine entity to Json using GetSetMethodNormalizer return fatal error
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'));