简体   繁体   English

symfony / FOSRestBundle:空的JSON响应(使用symfony体现的序列化程序)

[英]symfony/FOSRestBundle : empty JSON response (using the symfony embodied serializer)

I'm learning to build API with symfony (using FOSRestBundle). 我正在学习使用symfony构建API(使用FOSRestBundle)。 I'm following a french tutorial. 我正在学习法语教程。 Obviously, I first try to write the code by myself but even with a copy/paste, it keeps get me empty JSON array when I do a GET request to the appropriate route (rest-api.local/places). 显然,我首先尝试自己编写代码,但即使使用复制/粘贴,当我向相应的路径(rest-api.local / places)发出GET请求时,它仍然会让我获得空的JSON数组。

The code works OK if I "format" the code in php array: 如果我“格式化”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);
}

but then I try to serialize directly $places, using the view handler of fost Rest (in config.yml) 但后来我尝试直接序列化$ places,使用fost Rest的视图处理程序(在config.yml中)

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

and changing my function in my controller to the following code, I get my JSON response but without anything between "{ [],[],[]}" (and I do have 3 entries in my DB): 并将我的控制器中的功能更改为以下代码,我得到了我的JSON响应,但“{[],[],[]}”之间没有任何内容(我的数据库中有3个条目):

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

    return $places;
}

It's my first post on stackoverflow, so I hope my question is clear, Have a nice day. 这是我关于stackoverflow的第一篇文章,所以我希望我的问题很清楚,祝你有愉快的一天。

In my app/config/services.yml I've added this: 在我的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 }

I still can't get why it works but all of a sudden I've got a nice json in response. 我仍然无法理解为什么它有效但突然间我有一个很好的json作为回应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM