2017-07-26 129 views
0

我是PHP的初学者& Symfony 3和我有一个问题: json_encode返回空对象。您可以查看下面的图片和代码。空JSON返回 - Symfony3

/** 
* @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); 
} 

enter image description here

+1

你可以使用'JsonResponse'顺便说一句,看看这里:https://symfony.com/doc/current/components/http_foundation.html#creating-a-json-response –

回答

2

我认为这是东阳的的findAll()方法返回对象的数组,你应该在仓库中个性化的方法来得到一个数组结果,

public function findAllArray() 
{ 
    $qb = $this 
     ->createQueryBuilder('u') 
     ->select('u'); 
    return $qb->getQuery()->getArrayResult(); 
} 

另一件事,在Symfony中,您可以使用New JsonResponse发送Json数据

return new JsonResponse($restresult); 
+0

和symfony 3,你可以使用'return $ this-> json($ restresult)' – Michel

+0

现在又出现了另一个错误。无法找到模板“(查看:C:\ xampp \ htdocs \ my_project_name \ app/Resources/views,C:\ xampp \ htdocs \ my_project_name \ vendor \ symfony \ symfony \ src \ Symfony \ Bridge \ Twig/Resources /视图/表)。 – Olivio

0

储存库方法findAll返回对象数组。当您在具有私有属性的对象上使用json_encode时,它将返回{},除非您实施JsonSerialize interface