[英]Symfony2 - FOSRestBundle - Custom Serializer or JSON Output
如何使用FOSRestBundle創建自定義JSON輸出?
該代碼已經具有用於將實體和分頁的結果集轉換為JSON的方法。 以及生成唯一的URL以查看/編輯輸出的JSON中的實體。
這些如何與FOSRestBundle一起使用?
將Bars轉換為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可用。
使用自定義處理程序是可能的,請參閱文檔: 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輸出的數據格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.