Php 空JSON返回-Symfony3
我是PHP和Symfony 3的初学者,我有一个问题: json_encode返回空对象。您可以查看下面的图像和代码Php 空JSON返回-Symfony3,php,json,symfony,Php,Json,Symfony,我是PHP和Symfony 3的初学者,我有一个问题: json_encode返回空对象。您可以查看下面的图像和代码 /** * @Rest\Get("/user") */ public function getAction() { $restresult = $this->getDoctrine()->getRepository('AppBundle:User')->findAll(); if ($restresult === null) {
/**
* @Rest\Get("/user")
*/
public function getAction()
{
$restresult = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
if ($restresult === null) {
return new View("there are no users exist", Response::HTTP_NOT_FOUND);
}
return new Response(json_encode($restresult), Response::HTTP_OK);
}
我认为这是因为findAll()方法返回一个对象数组,您应该在存储库中对您的方法进行个性化设置以获得数组结果
public function findAllArray()
{
$qb = $this
->createQueryBuilder('u')
->select('u');
return $qb->getQuery()->getArrayResult();
}
另外,在Symfony中,您可以使用新的JsonResponse发送Json数据
return new JsonResponse($restresult);
存储库方法
findAll
返回对象数组。当您在具有私有属性的对象上使用json\u encode
时,它返回{}
,除非您实现。您可以使用JsonResponse
顺便说一句,看看这里:对于symfony 3,您可以使用返回$this->json($restresult)
现在出现了另一个错误。找不到模板“”(查找到:C:\xampp\htdocs\my_project\u name\app/Resources/views,C:\xampp\htdocs\my_project\u name\vendor\symfony\symfony\src\symfony\Bridge\Twig/Resources/views/Form)。