T
T
timager2021-02-14 16:21:22
symfony
timager, 2021-02-14 16:21:22

How to enable JMS\Serializer with required options in symfony by default?

I wrote a simple method in the controller that should return a serialized Event entity that contains related entities and circular references. Connected JMS\Serializer and serialize it like this:

/**
     * @Route("/event/{id}", name="event", methods={"GET"})
     * @param  Event  $event
     * @param  SerializerInterface  $serializer
     * @return Response
     */
    public function getEvent(Event $event, SerializerInterface $serializer): Response
    {
        return new JsonResponse($serializer->serialize($event, 'json'), 200, [], true);
    }


This works, but I would like to get rid of the need to pass such a large number of parameters in JsonResponse. Is it possible to configure JMS \ Serializer or achieve similar behavior from the built-in symfony serializer, so that you can simply pass it just write in the controller like this: or like this: I understand that you can just put it in a separate method or inherit from JsonResponse, but I would like to find out whether it is possible to achieve the desired behavior without such decisions.
return new JsonResponse($event);
return $this->json($event);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question