Symfony2-FOSRestBundle-自定义序列化程序或JSON输出

Symfony2-FOSRestBundle-自定义序列化程序或JSON输出,json,symfony,fosrestbundle,jmsserializerbundle,Json,Symfony,Fosrestbundle,Jmsserializerbundle,如何使用FOSRestBundle创建自定义JSON输出 代码中已有用于将实体和分页结果集转换为JSON的方法。以及生成唯一的URL以查看/编辑输出JSON中的实体 这些如何与FOSRestBundle一起使用 将条形图转换为JSON输出的自定义方法示例: $json = $this->getJsonFactory('Bar') ->dataTableFormat($data); return $this->jsonResponse($json)

如何使用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可用。

使用自定义处理程序这是可能的,请参阅文档:

工作示例:

    $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输出的数据格式。

使用自定义处理程序这是可能的,请参阅文档:

工作示例:

    $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输出的数据格式