php - symfony/FOSRestBundle : empty JSON response (using the symfony embodied serializer)

标签 php json rest symfony fosrestbundle

我正在学习使用 symfony 构建 API(使用 FOSRestBundle)。我正在学习法语教程。显然,我首先尝试自己编写代码,但即使使用复制/粘贴,当我向适当的路由 (rest-api.local/places) 发出 GET 请求时,它仍然让我得到空的 JSON 数组。

如果我在 php 数组中“格式化”代码,代码工作正常:

  public function getPlacesAction(Request $request)
{
    $places = $this->get('doctrine.orm.entity_manager')
            ->getRepository('AppBundle:Place')
            ->findAll();
    /* @var $places Place[] */

    $formatted = [];
    foreach ($places as $place) {
        $formatted[] = [
           'id' => $place->getId(),
           'name' => $place->getName(),
           'address' => $place->getAddress(),
        ];
    }

    return new JsonResponse($formatted);
}

但随后我尝试使用 fost Rest 的 View 处理程序(在 config.yml 中)直接序列化 $places

fos_rest:
routing_loader:
    include_format: false
view:
    view_response_listener: true
format_listener:
    rules:
        - { path: '^/', priorities: ['json'], fallback_format: 'json' }

并将 Controller 中的函数更改为以下代码,我得到了 JSON 响应,但“{ [],[],[]}”之间没有任何内容(我的数据库中确实有 3 个条目):

 public function getPlacesAction(Request $request)
{
    $places = $this->get('doctrine.orm.entity_manager')
            ->getRepository('AppBundle:Place')
            ->findAll();
    /* @var $places Place[] */

    return $places;
}

这是我关于 stackoverflow 的第一篇文章,所以我希望我的问题很清楚,祝你有愉快的一天。

最佳答案

在我的 app/config/services.yml 中,我添加了这个:

services:
    object_normalizer:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
        # Important! Tag this service or it wouldn't work
        tags:
            - { name: serializer.normalizer }

我仍然不明白为什么它会起作用,但突然之间我得到了一个很好的 json 作为响应。

关于php - symfony/FOSRestBundle : empty JSON response (using the symfony embodied serializer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38507035/

相关文章:

php - 字符串似乎是有效的 JSON,但 `json_decode()` 返回 NULL

javascript - 基于 JavaScript/JSON 的 OData 调用如何进行身份验证?

php - fatal error : Call to undefined method stdClass

php - mysql 查询(连接)和添加子查询

c# - 增加 jQuery/Javascript 中的 POST 数据大小

jquery - 数据表和jsonresult的排序问题

node.js - 如何在 "Code by Zapier"中编写 Node 获取(Rest-API)?

python - CCXT okex5 掉期合约 - 参数 posSide 错误

php - Symfony 2 与相关实体的验证

php - 从后台进程连接到Apple Push Notification Service