JMS Serializer: How to limit the depth of serialisation for an object graph

江枫思渺然 提交于 2019-11-30 23:39:53

Because I did not have access to the latest version of the serializer I had to find a workaround to the @MaxDepth. This may also help you.

Use @JMS\ExclusionPolicy("all") on all entities that are connected.

Now use @JMS\Expose only on those properties that you want to have serialize. On join relations only use this annotation in one direction. That will fix your problem.

namespace FinalConcept\TimeTracker\EntitiesBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;

/**
 * FinalConcept\TimeTracker\EntitiesBundle\Entity
 *
 * @JMS\ExclusionPolicy("all")
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="FinalConcept\TimeTracker\EntitiesBundle\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable
{
     /**
     * @JMS\Expose
     * @ORM\ManyToOne(targetEntity="company", inversedBy="users")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
     */
    private $company;
}

As of the latest version, using @MaxDepth() annotation and SerializationContext::create()->enableMaxDepthChecks() in the controller does the job.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!