title: Return array of serialized data in Symfony 4
body: <p>Symfony 4. I have 2 entites, <code>Cat</code> and <code>Dog</code>, which need to be serialized, then returned as a JSON response like this:</p>
  
  <pre><code>{
    'cats': // array of serialized cat data
    'dogs': // array of serialized dog data
  }
  </code></pre>
  
  <p>This is what I have so far:</p>
  
  <p>Controller:</p>
  
  <pre><code>public function index()
  {
      $repository = $this-&gt;getDoctrine()-&gt;getRepository(Cat::class);
      $cats = $repository-&gt;findAll();
      $repository = $this-&gt;getDoctrine()-&gt;getRepository(Dog::class);
      $dogs = $repository-&gt;findAll();
      return new JsonResponse([
          'cats' =&gt; $this-&gt;serializeData($cats, 'cats'),
          'dogs' =&gt; $this-&gt;serializeData($dogs, 'dogs'),
      ], 200);
  }
  </code></pre>
  
  <p>And my <code>serializeData</code> method looks like this:</p>
  
  <pre><code>protected function serializeData($data, $group)
  {
      return $this-&gt;json($data, $this-&gt;statusCode, [], [
          'groups' =&gt; [$group]
      ]);
  }
  </code></pre>
  
  <p>Here's a bit of the <code>Cat</code> entity:</p>
  
  <pre><code>use Symfony\Component\Serializer\Annotation\Groups;
  [...]
  /**
   * @ORM\Entity(repositoryClass="App\Repository\CatRepository")
   */
  class Cat
  {
      [...]
      /**
       * @ORM\Column(type="string", length=255)
       * @Groups("cats")
       */
      private $name;
      [...]
  }
  </code></pre>
  
  <p>The problem: when hitting this endpoint, instead of the data I get:</p>
  
  <pre><code>{
      "cats": {
          "headers": {}
      },
      "dogs": {
          "headers": {}
      }
  }
  </code></pre>
  
  <p><code>headers</code> is not part of either entity.</p>
  
  <p>EDIT:</p>
  
  <p>What else I've tried:</p>
  
  <pre><code>public function index()
  {
      $repository = $this-&gt;getDoctrine()-&gt;getRepository(Cat::class);
      $cats = $repository-&gt;findAll();
      $repository = $this-&gt;getDoctrine()-&gt;getRepository(Dog::class);
      $dogs = $repository-&gt;findAll();
      return new JsonResponse([
          'cats' =&gt; $this-&gt;container-&gt;get('serializer')-&gt;serialize($cats, 'json', [
              'groups' =&gt; ['cats'],
          ])
          'dogs' =&gt; $this-&gt;container-&gt;get('serializer')-&gt;serialize($dogs, 'json', [
              'groups' =&gt; ['dogs'],
          ])
      ], 200);
  }
  </code></pre>
  
  <p>This sort of works but <code>new JsonResponse</code> serializes the already serialized cats and dogs. And of course if I replace <code>new JsonResponse</code> with <code>new Response</code> I get the error</p>
  
  <blockquote>
    <p>The Response content must be a string or object implementing __toString(), "array" given.</p>
  </blockquote>