2017-02-11 48 views
0

我建立這需要一些輸出中實體JSON的API。我試圖找出是否最好將實體標準化並將其傳遞給JsonResponse,或者我應該將其序列化並將其傳遞給Response。兩者有什麼區別?Symfony的系列化響應VS標準化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); 
} 

有任何兩者之間的實際差值,除了事實上,我不必手動設置爲JsonResponseContent-Type頭?

回答

2

您可以比較串行使用的編碼器:JsonEncode什麼JsonResponse一樣。基本上它是一樣的。在引擎蓋下都使用json_encode來生成一個字符串。

我猜什麼感覺對你的項目是一個不錯的選擇。 JsonResponse主要是爲了方便起見,正如你已經注意到的那樣,只會自動設置正確的Content Type-header併爲你編碼爲json。

+0

你說得對。我確實看過他們早些時候做的事情,但我挖得更深。 'JsonResponse'設置了一些[編碼選項](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/JsonResponse.php#L32),這使得編碼HTML是安全的。它還設置了「Content-Type」標題。所以我想我會使用JsonEncode,所以我不必自己做這些事情。 –

0

從我明白約Symfony的序列化,正常化是其中對象被映射到一個關聯數組序列化過程的一部分,該陣列隨後被編碼到一個普通的JSON對象,完成序列化。

實際上是使用規範化功能你可以修改代碼使用Response類代替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的代碼,但相信它的一部分將是規範化功能。你可以在symfony的文檔的解釋:http://symfony.com/doc/current/components/serializer.html enter image description here

+0

是的,我知道我可以做到這一點。我更關注每種序列化數據的具體差異(優點/缺點)。 –