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

 

Leave a Reply

Your email address will not be published. Required fields are marked *