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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – symfony / FOSRestBundle:空的JSON响应(使用symfony体现的序列化程序)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习使用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);
}

但后来我尝试直接序列化$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' }

并将我的控制器中的功能改为以下代码,我得到了我的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:空的JSON响应(使用symfony体现的序列化程序)全部内容,希望文章能够帮你解决php – symfony / FOSRestBundle:空的JSON响应(使用symfony体现的序列化程序)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。