0

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.

2 Answers 2

1

You could use the Symfony Serializer component:

https://symfony.com/doc/master/components/serializer.html

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - in the edit to my question I've shown what happens when I use the serializer directly.
1

well, method $this->json returns an JsonResponse so the whole stuff returns an JsonResponse(JsonResponse...) - source

public function index()
{
...
    return $this->json(['cats' => $cats, 'dogs' => $dogs], 200, [], ['groups' => ['cats', 'dogs']]);
}

8 Comments

If I remove the @group annotations, I remove the functionality offered by @group annotations, which I have put in there because I need it.
well, so I think you need to combine it by yourself. look at the source code and you'll get how the serializer is used - just serialize $cats and $dogs. I'll try to update the post in cuple of minutes - but I can't check it
Thanks for persisting, I've edited my answer to show what happens when I follow your approach.
do you have some annotations within the action methos in the controller?
I don't want to waste any more of your time on this, I think my use case is a bit niche, and too long to explain in a single post. Thanks for your help!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.