일부 엔티티를 JSON으로 출력해야하는 API를 빌드하고 있습니다. 엔티티를 정규화하고 JsonResponse
으로 전달하는 것이 더 좋은지 또는이를 serialize하고 Response
으로 전달해야 하는지를 판단하려고합니다. 둘의 차이점은 무엇입니까? Symfony 직렬화 응답 대 정규화 된 JsonResponse
/**
* 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);
}
는 둘 사이의 실제 차이는 사실 외에 내가 수동으로
JsonResponse
에 대한
Content-Type
헤더를 설정할 필요가 없습니다 있나요?
맞습니다. 이전에 한 일을 살펴 봤지만 깊이 파고 들었습니다. 'JsonResponse'는 HTML 인코딩을 안전하게하는 일부 [인코딩 옵션] (https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/JsonResponse.php#L32)을 설정합니다. 또한'Content-Type' 헤더를 설정합니다. 그래서 나는 JsonEncode를 사용할 것이므로 그러한 것들을 직접 할 필요가 없다고 생각합니다. –