2017-02-11 9 views
0

私はいくつかのエンティティをJSONとして出力する必要があるAPIを構築しています。エンティティを正規化してJsonResponseに渡す方が良いか、それをシリアル化して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); 
} 

2の間の任意の実際の差は事実のほかに、私は手動でJsonResponseためContent-Typeヘッダーを設定する必要はありません、ありますか?

答えて

2

シリアライザで使用されるエンコーダをJsonEncodeと比較すると、JsonResponseと比較できます。基本的には同じです。フードの下では、両方ともjson_encodeを使用して文字列を生成します。

私はあなたのプロジェクトが正しいと感じることは何でも良い選択だと思います。主にJsonResponseは便宜上のものであり、すでに述べたように、自動的に正しいContent Typeヘッダーが設定され、jsonというエンコーディングが自動的に行われます。

+0

あなたは正しいです。私は彼らが以前に何をしたかを見てきましたが、私はもっと深く掘りました。 'JsonResponse'は、HTMLをエンコードするのに安全ないくつかの[エンコーディングオプション](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/JsonResponse.php#L32)を設定します。 'Content-Type'ヘッダも設定します。だから私はJsonEncodeを使うつもりだと思うので、私はそれらを自分でやる必要はない。 –

0

正規化は、オブジェクトが連想配列にマップされるシリアライゼーションプロセスの一部です。この配列はプレーンな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のコードをチェックし、それの一部がされると信じていません正規化関数。あなたはsymfonyの文書で説明を見つけることができます:http://symfony.com/doc/current/components/serializer.html enter image description here

+0

はい、私はそれを行うことができることを知っています。私は、データをシリアライズするそれぞれの方法の具体的な違い(賛否両論)が何であるかをより詳しく説明します。 –

関連する問題