[symfony] ControllerでJsonを返す

PHP、SymfonyでJsonを返すAPIを作ろうとしていたら思ったより難しかったのでメモ

ORMapperはDoctrineです。

 

Jsonを返すためにはアクションメソッド内でSerializerを利用する必要があります。

コンストラクタでシリアライザを初期化してあとはResponseクラスに入れて返すと無事にJsonが返却できます

 


class TodoController extends Controller
{
private $encoders;
private $normalizers;

private $serializer;

public function __construct()
{
$this->encoders = array(new XmlEncoder(), new JsonEncoder());
$this->normalizers = array(new ObjectNormalizer());
$this->serializer = new Serializer($this->normalizers, $this->encoders);
}
/**
* @Route("/", name="todo_index", methods="GET")
*/
public function index(TodoRepository $todoRepository): Response
{

$items = $todoRepository->findAll();
$jsonContent = $this->serializer->serialize($items, 'json',['json_encode_options' => JSON_UNESCAPED_SLASHES]);
$res = new Response($jsonContent);
$res->headers->set('Content-Type','application/json');
return $res;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.