jsonsymfonyjmsserializerbundle

Symfony use JMS Serializer with JsonResponse


In a Symfony application is it possible to use the JMS serializer when calling JsonResponse() on a controller`?

$response = new ApiResponse(ApiResponse::STATUS_SUCCESS);
return new JsonResponse($response); // <-- I would like to use the JMS serializer

Solution

  • In case of symfony 3 you can use this:

        $json = $this->get("serializer")->serialize($response, 'json');
        return new JsonResponse($json, 200, [], true);
    

    In case of symfony 2 you don't have the last argument, but you can use a standart Reponse and specify the content type:

        $response->headers->set('Content-Type', 'application/json');