The best way is to use the useCircularReferenceLimit method. As has been clearly explained in this post.
But we have another option. Alternatively, there is a way to ignore attributes from the source object. We can ignore this if we definitely do not need it in a serialized object. The advantage of this solution is that the serialized object is smaller and easier to read, and the disadvantage is that we will no longer refer to the ignored attribute.
Symfony 2.3 - 4.1
To remove these attributes, use the setIgnoredAttributes () method in the normalizer definition:
use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; $normalizer = new ObjectNormalizer(); $normalizer->setIgnoredAttributes(array('age')); $encoder = new JsonEncoder(); $serializer = new Serializer(array($normalizer), array($encoder)); $serializer->serialize($person, 'json');
The setIgnoredAttributes() method was introduced in Symfony 2.3.
Prior to Symfony 2.7, attributes were only ignored during serialization. Starting with Symfony 2.7, they are also ignored during deserialization.
Symfony 4.2 - 5.0
The setIgnoredAttributes() method, which was used as an alternative to the ignored_attributes option, is deprecated in Symfony 4.2.
To remove these attributes, provide the array using the ignored_attributes key in the context parameter of the desired serializer method:
use Acme\Person; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; $person = new Person(); $person->setName('foo'); $person->setAge(99); $normalizer = new ObjectNormalizer(); $encoder = new JsonEncoder(); $serializer = new Serializer([$normalizer], [$encoder]); $serializer->serialize($person, 'json', ['ignored_attributes' => ['age']]);
In my Symfony 3.4 projects, I use a combination of the two methods setIgnoredAttributes() and setCircularReferenceLimit() , and it works fine.
Source: https://symfony.com/doc/3.4/components/serializer.html