2017-07-26 74 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