StockBreak
StockBreak

Reputation: 2895

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

Upvotes: 2

Views: 4062

Answers (3)

Erfan
Erfan

Reputation: 1192

And since Symfony 5 one can simply call json function.
Under the hood it uses the symfony serializer service.

public function index(): Response {
    $data = ... some json data
    return $this->json($data);
}

Upvotes: 0

Vural
Vural

Reputation: 8748

For Symfony 4+ the DI for serialization can be used this way if autowire = true

In Symfony 4 the autowire is already set true as default.

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * ... anything
 *
 * @return JsonResponse
 */
public action(SerializerInterface $serializer) {
    return new JsonResponse($serializer->serialize($response, 'json'), 200, [], true);
}

Upvotes: 2

Vladislav
Vladislav

Reputation: 357

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');

Upvotes: 5

Related Questions