我正在使用最新版本的symfony 3.3
我正在尝试返回json但是我收到错误
这是我的控制者:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
class ApiController extends Controller{
/**
* @Route("home", name="api_home")
*/
public function indexAction(SerializerInterface $serializer)
{
$entity = $this->getDoctrine()
->getRepository('AppBundle:User')
->findAll();
$json = $serializer->serialize($entity,'json', ['groups' => ['User']]);
return new JsonResponse($json, 200, [], true);
}
}
on services.yml:
services:
_defaults:
public: false
autowire: false
autoconfigure: true
config.yml
serializer:
enabled: true
enable_annotations: true
我收到错误:
Controller "AppBundle\Controller\ApiController::indexAction()" requires that you provide a value for the "$serializer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
我尝试在$ json之前死去
但同样的错误
感谢
答案 0 :(得分:2)
这只是因为我在services.yml
上没有这个 AppBundle\Controller\:
resource: '../../src/AppBundle/Controller/*'
public: true
tags: ['controller.service_arguments']
答案 1 :(得分:1)
action方法可以从请求转换Request属性或params(您需要从容器中检索的服务),请尝试以下代码:
/**
* @Route("home", name="api_home")
*/
public function indexAction()
{
$serializer = $this->get('serializer');
$entity = $this->getDoctrine()
->getRepository('AppBundle:User')
->findAll();
$json = $serializer->serialize($entity,'json', ['groups' => ['User']]);
return new JsonResponse($json, 200, []);
}
希望这个帮助