如何使用FOSRestBundle创建自定义JSON输出?
代码已经有一些方法,用于将实体和分页的结果集转换为JSON。以及生成唯一的URL来查看/编辑输出的JSON中的实体。
如何将它们与FOSRestBundle一起使用?
将条形图转换为JSON输出的自定义方法示例:
$json = $this->getJsonFactory('Bar')
->dataTableFormat($data);
return $this->jsonResponse($json); 如何使用此自定义方法作为视图中JSON的输出?
$data = $this->getDoctrine()->getRepository('Foo:Bar')
->findAll();
$view = $this->view($data, 200)
->setTemplate("Foo:Bar:index.html.twig")
->setTemplateVar('bars')
;如果有帮助的话,JMSSerializerBundle是可用的。
发布于 2015-10-09 11:39:53
使用自定义处理程序是可能的,请参阅docs:http://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#custom-handler
工作实例:
$handler = $this->get('fos_rest.view_handler');
if (!$handler->isFormatTemplating($view->getFormat())) {
$templatingHandler = function ($handler, $view, $request) {
$data = $this->getJsonFactory('Bar')
->dataTableFormat($$view->getData());
$view->setData($data);
return $handler->createResponse($view, $request, 'json');
};
$handler->registerHandler('json', $templatingHandler);
}$templatingHandler方法处理调用JsonFactory和设置json输出的数据格式。
https://stackoverflow.com/questions/33032601
复制相似问题