Skip to main content

Fix JSON serialization root as object instead of array in Symfony

JMS Serializer is perhaps my favorite and most frequently used open source package, and I am infinitely thankful for Johannes Schmitt for his contribution.

However, with heavy usage of Annotations JMS can become frustrating at times. Especially when building API data that you’re expecting to be formatted as an array or object and standardizing the behavior.

With the use of @MaxDepth, you’ll find that your recursive entity serialization may end up serialized as an object of nested objects, instead of an array of objects as you expect.

Check this issue for a deeper discussion on variations of the same problem, and also the solution implemented here.

Expected

Actual

The fix for this is actually quite simple:

JsonSerializationVisitor.php

parameters.yml

 

“Smart” Accessor in Doctrine Entity

Easily add some logic to filter out specific entities from an ArrayCollection in Symfony2. In this simple example, I wrote an app that had Node, and Comment entities separately, as well as an explicitly defined NodeComment entity. In my Node entity, I want to serialize all of the associated comments. But rather than call ->getNodeComments() and then filter in AngularJS (or Twig, or whatever else for that matter), I just want to know that my object node.comments are the actual comments I care about.

The Entity property

The Accessor

Now, my serialized object.comments are the actual comments, instead of the ManyToMany Entity.