Reputation: 4811
I'm building an API which needs to ouput some entities as JSON. I'm trying to figure out if it's better to normalize the entity and pass it to JsonResponse
or if I should serialize it and pass it to Response
. What is the difference between the two?
/**
* Returning a Response
*/
public function getEntityAction($id)
{
$entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);
$json = $this->get('serializer')->serialize($entity);
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response
}
/**
* Returning a JsonResponse.
*/
public function getEntityAction($id)
{
$entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);
$array = $this->get('serializer')->normalize($entity);
return new JsonResponse($array);
}
Is there any actual difference between the two, besides the fact I don't have to manually set the Content-Type
header for a JsonResponse
?
Upvotes: 1
Views: 2596
Reputation: 2522
From what I understand about Symfony serialization, normalization is a part of serialization process in which the object is mapped to an associative array, this array is then encoded to a plain JSON object, accomplishing the serialization.
Your code using normalize function in fact can be modified to use Response class instead of JsonResponse:
/**
* Returning a JsonResponse.
*/
public function getEntityAction($id)
{
$entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);
$array = $this->get('serializer')->normalize($entity);
$response = new Response(json_encode($array));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
I haven't checked the Symfony code for the serialize function, but believe part of it will be the normalize function. You can find the explain in symfony doc: http://symfony.com/doc/current/components/serializer.html
Upvotes: 0
Reputation: 17166
You can compare the encoder used by the Serializer: JsonEncode with what JsonResponse does. Essentially it's the same. Under the hood both use json_encode
to generate a string.
I guess whatever feels right for your project is a good choice. JsonResponse is mainly for convenience and as you already noted will just automatically set the correct Content Type-header and do the encoding as json for you.
Upvotes: 2