【问题标题】:FOSRestBundle how to return a JsonResponseFOSRestBundle 如何返回 JsonResponse
【发布时间】:2014-10-16 19:47:40
【问题描述】:

这方面有很多话题,但我找到的答案都不适合我。

我想使用 FOSRestBundle 构建一个返回 JSON 的 API(目前,我可能会在未来添加 XML)。

当我向我的路线发出请求时,出现以下异常:

[
   {
       message: "Unable to find template "".",
       class: "InvalidArgumentException",
   ...

我有一个动态构建路由的控制器。我配置了 json 格式,并返回一个 View,其中包含要在 json 中序列化的数据数组。如果不使用 FOSRestBundle,我会返回一个 JSONResponse 并完成它,但正如我所说,我最终会在未来添加其他格式,所以我想以正确的方式做事。

这是我的路线:

categories:
    type: rest
    resource: Certiz\Bundle\ExamBundle\Controller\CategoryController
    prefix: /api
    requirements:
        _format: "json"

我要求以下路线: /api/类别

我的 config.yml :

fos_rest:
view:
    formats:
        json: true
        xml: false
        html: false
        rss: false
    templating_formats:
        json: true
        xml: false
        html: false
        rss: false
    view_response_listener: 'force'
routing_loader:
    default_format: json
    include_format: true
exception:
    codes:
        'Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException': 401
    messages:
        'Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException': true

jms_serializer:
    metadata:
        directories:
            exam:
                namespace_prefix: "Certiz\\Bundle\\ExamBundle"
                path: "@CertizExamBundle/Resources/config/serializer"

还有我的控制器:

public function getCategoriesAction()
{
    $categories = $this
        ->getDoctrine()
        ->getManager()
        ->getRepository('Certiz\Bundle\ExamBundle\Entity\Category')
        ->getTree();

    return View::create()
        ->setStatusCode(200)
        ->setData($categories)
   ;
} // "get_categories" [GET] /categories

我使用 symfony 2.5 和 FOSRestBundle 1.4.2。

问候

【问题讨论】:

    标签: symfony fosrestbundle


    【解决方案1】:

    我发现了问题所在。在我的 fos_rest config.yml 中,我说过 json 格式的响应应该由模板引擎而不是序列化程序来管理。

    我将配置更改为:

    fos_rest:
        view:
            templating_formats:
                json: false
    

    【讨论】:

      【解决方案2】:

      来自 FOSRestBundle 文档:

      格式和模板格式设置决定了哪些格式 分别由序列化程序和模板支持 层。换句话说,在 templating_formats 中列出的任何格式都将 需要一个模板来使用模板服务进行渲染,而 格式中列出的任何格式都将使用序列化程序进行渲染。 对于这两种设置,false 值意味着给定的格式是 已禁用。

      所以我认为您应该从您的配置中排除未使用的格式,并留下您真正需要的内容,以使您的 conf 更具可读性:

      fos_rest:
          view:
              formats:
                  json: true
              templating_formats:
                  html: true
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-07
        • 2021-03-19
        • 2019-01-07
        • 2017-12-24
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多