2
votes

I am using the JMS Serializer bundle to serialize Symfony entities into json. Everything is working fine until I start using the MaxDepth annotation to avoid a deep recursion.

I have an entity called "Category" which has "Subcategories", if I don't make use of MaxDepth annotation when I serialize it, it works perfectly and generates a json object the way it should be with the complete tree of subcategories:

{
    "id": 1,
    "name": "Category 1",
    "subcategories": [{
        "id": 3,
        "name": "Category 1-1",
        "subcategories": [{
            "id": 7,
            "name": "Category 1-1-1",
            "subcategories": []
        }]
    }, {
        "id": 4,
        "name": "Category 1-2",
        "subcategories": []
    }]
}

I would like to have only the first level of subcategories serialized, so I have tried configuring my entity this way:

class Category
{
    ....

    /**
    * @ORM\OneToMany(targetEntity="Category", mappedBy="parentCategory")
    * @MaxDepth(1) 
    */
    private $subcategories;    

    ....    

}

But for some reason I don't understand when I enable the maxdepth checks, using the following code:

$serializedObj = $jms->serialize($obj, 'json', SerializationContext::create()->enableMaxDepthChecks());

I get this weird result (no subcategory encoded but it knows that there are two):

{
    "id": 1,
    "name": "Categoria 1",
    "subcategories": [{}, {}]
}

Any idea on what's going on?

Thank you!

2
Are you tried to set @MaxDepth(2) ? - Max Lipsky
I've been encountering the same issue. I'm going nuts because MaxDepth annotation does not work (yes I have serializerEnableMaxDepthChecks=true). - Lord Zed
Lexxx has right. In child entities you have to set Groups the same same like you pass in setGroups() parameter (in controller method) - Paweł Owczarek
Hey thank you for your amazing response. is it possible to mention @MaxDepth on the hole class?? - famas23

2 Answers

4
votes

I had a similar problem and fixed is this way:

In the Student class:

/**
 * @ORM\ManyToOne(targetEntity="school", inversedBy="student")
 * @ORM\JoinColumn(name="school_id", referencedColumnName="id")
 * @JMS\Serializer\Annotation\MaxDepth(2)
 */
protected $school;

In the Student controller:

/**
 * @FOS\RestBundle\Controller\Annotations\View(serializerEnableMaxDepthChecks=true)
 */
public function getStudentsAction() {
    $students = $this->getDoctrine()
    ->getRepository('AppBundle:Student')
    ->findAll();
    return $students;
}

Nothing of the school gets serialized, this is exactly what I needed!

1
votes

when I once had a similar issue, it was caused by not using the same serializer group in the child entity, so it gave an empty object (no properties serialized)