Tapakan Tapakan - 1 year ago 164
PHP Question

Symfony JsonResponse with Serializer

I have a small problem. Maybe someone have an a idea.

I use Serializer in the following way. The problem that function json_encode is applied two times.

First when i call $serializer->serialize($post, 'json');

Second time in $response->setData();

So, to decode i need call function two times.

Any ideas?

$encoders = [
new JsonEncoder()
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
$normalizers = [$normalizer];
$serializer = new Serializer($normalizers, $encoders);

$response = new JsonResponse();
'status' => true,
'data' => $serializer->serialize($post, 'json')

return $response;

Answer Source

The object is encoded twice because you use a jsonresponse, use a simple response instead. In addition encode the entire data, not only part of them . As example:

$responseData = [
    'status' => true,
    'data'   => $post

$response = new Response(
   $serializer->serialize($$responseData, 'json'),
   ['Content-type' => 'application/json']

return $response:

Hope this help