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;
To return a json string
instead of an array
use the JsonResponse::fromJsonString
method:
return JsonResponse::fromJsonString($serializer->serialize($data, 'json'));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With