【问题标题】:Symfony2 - FOSRestBundle - Custom Serializer or JSON OutputSymfony2 - FOSRestBundle - 自定义序列化器或 JSON 输出
【发布时间】:2016-01-07 01:37:53
【问题描述】:

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

【问题讨论】:

    标签: json symfony fosrestbundle jmsserializerbundle


    【解决方案1】:

    可以使用自定义处理程序,请参阅文档: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 输出的数据格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-20
      • 2013-03-05
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多