Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony JsonResponse with Serializer

Tags:

json

php

symfony

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();
$response->setData([
    'status' => true,
    'data'   => $serializer->serialize($post, 'json')
]);

return $response;
like image 310
Tapakan Avatar asked Oct 16 '16 17:10

Tapakan


2 Answers

To return a json string instead of an array use the JsonResponse::fromJsonString method:

return JsonResponse::fromJsonString($serializer->serialize($data, 'json'));
like image 51
Simon Epskamp Avatar answered Nov 04 '22 14:11

Simon Epskamp


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'),
   Response::HTTP_OK,
   ['Content-type' => 'application/json']
);

return $response:

Hope this help

like image 33
Matteo Avatar answered Nov 04 '22 13:11

Matteo