2017-02-11 2 views
0

일부 엔티티를 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 헤더를 설정할 필요가 없습니다 있나요?

답변

2

시리얼 화기에서 사용하는 인코더 : JsonEncodeJsonResponse을 비교할 수 있습니다. 본질적으로 동일합니다. 후드 아래에서 문자열을 생성하려면 json_encode을 사용하십시오.

프로젝트에 맞는 것이 무엇이든지 좋은 선택이라고 생각합니다. JsonResponse는 주로 편의를 위해 이미 언급했듯이 자동으로 올바른 Content Type-header를 설정하고 인코딩을 json으로 처리합니다.

+0

맞습니다. 이전에 한 일을 살펴 봤지만 깊이 파고 들었습니다. 'JsonResponse'는 HTML 인코딩을 안전하게하는 일부 [인코딩 옵션] (https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/JsonResponse.php#L32)을 설정합니다. 또한'Content-Type' 헤더를 설정합니다. 그래서 나는 JsonEncode를 사용할 것이므로 그러한 것들을 직접 할 필요가 없다고 생각합니다. –

0

Symfony 직렬화에 대해 이해 한대로 정규화는 객체가 연관 배열에 매핑되는 직렬화 프로세스의 일부로,이 배열은 일반 JSON 객체로 인코딩되어 직렬화를 수행합니다.

사실 정상화 기능을 사용하여 코드 대신 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; 
} 

을하지만, 생각의 일부가 될 것입니다 정상화 기능. symfony 문서에서 설명을 찾을 수 있습니다. http://symfony.com/doc/current/components/serializer.html enter image description here

+0

예, 할 수 있다는 것을 알고 있습니다. 나는 데이터를 직렬화하는 각 방법의 구체적인 차이점 (장단점)을 알고있다. –