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